109 lines
3.0 KiB
JavaScript
109 lines
3.0 KiB
JavaScript
import Koa from 'koa';
|
|
import bodyParser from 'koa-bodyparser';
|
|
import cors from 'koa-cors';
|
|
import mount from 'koa-mount';
|
|
import serve from 'koa-static';
|
|
import http from 'http';
|
|
import { fileURLToPath } from 'url';
|
|
import { DBModel } from './models/index.js';
|
|
import registerRoutes from './routes/index.js';
|
|
import ResponseUtil from './utils/responseUtil.js';
|
|
|
|
const STATIC_DIR = fileURLToPath(new URL('./statics', import.meta.url));
|
|
|
|
// 语音/图片识别与培训报名材料走 base64 JSON,单请求体可能达到数 MB;
|
|
// 只对这些前缀放宽解析上限,其余接口维持 1MB,避免全局放大内存占用
|
|
const LARGE_BODY_PREFIXES = ['/health/ai/', '/health/training-application'];
|
|
const DEFAULT_BODY_LIMIT = '1mb';
|
|
const LARGE_BODY_LIMIT = '20mb';
|
|
const defaultBodyParser = bodyParser({
|
|
jsonLimit: DEFAULT_BODY_LIMIT,
|
|
formLimit: DEFAULT_BODY_LIMIT,
|
|
textLimit: DEFAULT_BODY_LIMIT,
|
|
});
|
|
const largeBodyParser = bodyParser({
|
|
jsonLimit: LARGE_BODY_LIMIT,
|
|
formLimit: LARGE_BODY_LIMIT,
|
|
textLimit: LARGE_BODY_LIMIT,
|
|
});
|
|
|
|
class APP {
|
|
constructor() {
|
|
this.app = new Koa();
|
|
this.setupDB();
|
|
this.setupMiddleware();
|
|
this.setupRoutes();
|
|
this.setupFallback();
|
|
}
|
|
|
|
setupDB() {
|
|
DBModel.init();
|
|
}
|
|
|
|
setupMiddleware() {
|
|
// 服务在 nginx 之后,需信任代理头才能拿到真实客户端 IP
|
|
// (否则 ctx.ip 恒为 127.0.0.1,限流会变成全站共享一个桶)
|
|
this.app.proxy = true;
|
|
this.app.proxyIpHeader = "X-Real-IP";
|
|
|
|
this.app.use(mount('/static', serve(STATIC_DIR)));
|
|
this.app.use(cors());
|
|
this.app.use((ctx, next) => {
|
|
const parser = LARGE_BODY_PREFIXES.some((prefix) => ctx.path.startsWith(prefix))
|
|
? largeBodyParser
|
|
: defaultBodyParser;
|
|
return parser(ctx, next);
|
|
});
|
|
|
|
this.app.use(async (ctx, next) => {
|
|
const start = Date.now();
|
|
await next();
|
|
const ms = Date.now() - start;
|
|
// 只记录路径,不记录查询串:URL 里可能带 token、手机号等敏感参数,
|
|
// 一旦进入 access log 就等于把凭证/隐私落盘
|
|
console.log(`${ctx.method} ${ctx.path} - ${ctx.status} - ${ms}ms`);
|
|
});
|
|
}
|
|
|
|
setupRoutes() {
|
|
this.app.use(async (ctx, next) => {
|
|
if (ctx.path === '/') {
|
|
ResponseUtil.success(ctx, { name: 'attendant-api', version: '1.0.0' });
|
|
return;
|
|
}
|
|
await next();
|
|
});
|
|
|
|
this.app._router = registerRoutes(this.app);
|
|
}
|
|
|
|
setupFallback() {
|
|
this.app.use(async (ctx) => {
|
|
ctx.status = 404;
|
|
ctx.body = { code: 404, msg: 'Not Found' };
|
|
});
|
|
}
|
|
|
|
start(port) {
|
|
this.server = http.createServer(this.app.callback());
|
|
this.server.listen(port, () => {
|
|
console.log(`Server: running on http://localhost:${port}`);
|
|
});
|
|
}
|
|
|
|
stop() {
|
|
if (this.server) {
|
|
this.server.close();
|
|
this.server = null;
|
|
console.log('Server stopped');
|
|
}
|
|
}
|
|
|
|
static createKoaApp() {
|
|
const instance = new APP();
|
|
return instance.app;
|
|
}
|
|
}
|
|
|
|
export { APP };
|