nfp_sites/api/serve.mjs

57 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-02-19 11:34:52 +00:00
import send from 'koa-send'
2019-09-23 19:19:08 +00:00
import defaults from './defaults.mjs'
import access from './access/index.mjs'
import { restrict } from './access/middleware.mjs'
import { serveIndex } from './serveindex.mjs'
2019-10-02 00:16:11 +00:00
import config from './config.mjs'
2019-10-01 03:45:44 +00:00
const restrictAdmin = restrict(access.Manager)
2019-02-19 11:34:52 +00:00
export function serve(docRoot, pathname, options = {}) {
options.root = docRoot
return async (ctx, next) => {
let opts = defaults({}, options)
2019-02-19 11:34:52 +00:00
if (ctx.request.method === 'OPTIONS') return
let filepath = ctx.path.replace(pathname, '')
if (filepath === '/') {
filepath = '/index.html'
}
if (filepath.endsWith('.jpg')
|| filepath.endsWith('.png')
|| filepath.endsWith('.js')
|| filepath.endsWith('.css')
|| filepath.endsWith('.svg')) {
if (filepath.indexOf('admin') === -1) {
opts = defaults({ maxage: 2592000 * 1000 }, opts)
}
}
2019-10-01 03:45:44 +00:00
if (filepath === '/index.html') {
return serveIndex(ctx, '/')
}
if (filepath.indexOf('admin') >= 0
&& (filepath.indexOf('js') >= 0
|| filepath.indexOf('css') >= 0)) {
2019-10-02 00:16:11 +00:00
if (filepath.indexOf('.map') === -1) {
await restrictAdmin(ctx)
ctx.set('Cache-Control', 'no-store, no-cache, must-revalidate')
} else if (config.get('NODE_ENV') !== 'development') {
ctx.status = 404
return
}
2019-10-01 03:45:44 +00:00
}
return send(ctx, filepath, opts).catch((er) => {
2019-02-19 11:34:52 +00:00
if (er.code === 'ENOENT' && er.status === 404) {
return serveIndex(ctx, filepath)
2019-10-01 03:45:44 +00:00
// return send(ctx, '/index.html', options)
2019-02-19 11:34:52 +00:00
}
})
}
}