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

54 lines
1.2 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-04 10:44:16 +00:00
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())
app.use(Static(new URL('public', import.meta.url).pathname))
// 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`)
})
2021-02-04 10:44:16 +00:00
console.log('url', import.meta.url)
2021-01-27 17:09:17 +00:00
// 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