certd/packages/ui/certd-server/app.js

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2021-01-27 17:09:17 +00:00
import Koa from 'koa'
import json from 'koa-json'
import onerror from 'koa-onerror'
import bodyparser from 'koa-bodyparser'
import logger from 'koa-logger'
import Static from 'koa-static'
import fs from 'fs'
import _ from 'lodash-es'
2021-02-08 06:31:12 +00:00
import './install.js'
2021-02-09 07:42:10 +00:00
import pathUtil from './utils/util.path.js'
2021-02-09 10:05:01 +00:00
import compress from 'koa-compress'
2021-01-27 17:09:17 +00:00
const app = new Koa()
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
2021-02-09 10:40:29 +00:00
// gzip
// app.use(compress({ threshold: 5120 }))
2021-01-27 17:09:17 +00:00
2021-02-09 07:42:10 +00:00
const staticPlugin = Static(pathUtil.join('public'), {
2021-02-09 10:05:01 +00:00
maxage: 30 * 24 * 60 * 3600,
gzip: true
2021-02-09 07:42:10 +00:00
})
app.use(staticPlugin)
2021-01-27 17:09:17 +00:00
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
2021-02-04 10:44:16 +00:00
const files = fs.readdirSync(new URL('controllers/', import.meta.url))
2021-01-27 17:09:17 +00:00
// 过滤出.js文件:
const jsFiles = files.filter((f) => {
return f.endsWith('.js')
})
_.forEach(jsFiles, async item => {
2021-02-04 10:44:16 +00:00
let mapping = await import(new URL('controllers/' + item, import.meta.url))
2021-01-27 17:09:17 +00:00
mapping = mapping.default
app.use(mapping.routes(), mapping.allowedMethods())
})
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
})
console.log('http://localhost:3000/')
export default app