storage-upload/api/server.mjs

67 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

import { performance } from 'perf_hooks'
import { Flaska, QueryHandler } from 'flaska'
import TestRoutes from './test/routes.mjs'
import MediaRoutes from './media/routes.mjs'
import config from './config.mjs'
import log from './log.mjs'
const app = new Flaska({
log: log,
})
app.before(function(ctx) {
ctx.__started = performance.now()
ctx.log = ctx.log.child({
ip: ctx.req.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress,
})
})
app.after(function(ctx) {
let ended = performance.now() - ctx.__started
let logger = ctx.log.info
if (ctx.status >= 400) {
logger = ctx.log.warn
}
logger.apply(ctx.log, [{
path: ctx.url,
status: ctx.status,
ms: Math.round(ended),
}, 'Request finished'])
})
app.onerror(function(err, ctx) {
if (err.status && err.status >= 400 && err.status < 500) {
ctx.log.warn(err.message)
} else {
ctx.log.error(err)
}
ctx.status = err.status || 500
ctx.body = {
status: ctx.status,
message: err.message,
}
})
const test = new TestRoutes()
app.get('/', test.static.bind(test))
app.get('/error', test.error.bind(test))
const media = new MediaRoutes()
media.init().then(function() {}, function(err) {
log.error(err, 'Error initing media')
})
app.get('/media', [QueryHandler()], media.listFiles.bind(media))
app.get('/media/:site', media.listPublicFiles.bind(media))
app.post('/media', [QueryHandler()], media.upload.bind(media))
app.post('/media/noprefix', [QueryHandler()], media.uploadNoPrefix.bind(media))
app.post('/media/resize', [QueryHandler()], media.resize.bind(media))
app.delete('/media/:filename', [QueryHandler()], media.remove.bind(media))
app.listen(config.get('server:port'), function(a,b) {
log.info(`Server listening at ${config.get('server:port')}`)
})
export default app