Files
api_health/app.js
T
lik 4c2db2b6df feat: 陪诊师入驻申请与审核链路
- 新增 attendant_application 表与 5 个接口:提交/我的申请/审核列表/
  材料大图/审批,/mine 注册在 /:id 之前
- 提交侧按员工档案岗位分支:在职陪诊师与管理员及其他岗位 409 拒绝,
  转岗由管理员后台显式操作;停用陪诊师可重新申请
- 审批两步走不依赖事务:条件更新抢占 pending,ensureEmployee 单条
  条件 upsert 幂等建档(只放行无档案或已有 attendant 档案),
  失败靠 approvedEmployeeId 为空续跑
- 岗位冲突时申请单条件回滚为 pending,不卡死在"已通过但未建档"
- employee.userId 加 partial unique 索引并移除 employeeNo 默认值,
  附迁移与存量校验脚本;员工管理端绑定账号查重与 userIdSource 标记
- 证件照复用 parseImage(单张 3MB),入驻前缀放宽请求体上限;
  索引创建失败改为记日志,避免启动即崩
2026-11-08 12:00:32 +08:00

161 lines
4.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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', '/health/attendant-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,
});
// 客户端错误只回通用文案:body-parser / 框架的原始 message 可能带内部字段名
const CLIENT_ERROR_MESSAGES = {
400: "请求参数格式不正确",
401: "未授权",
403: "禁止访问",
404: "资源不存在",
405: "请求方法不支持",
413: "请求体过大",
415: "不支持的请求格式",
429: "操作过于频繁,请稍后再试",
};
/**
* 统一错误出口
*
* 业务 handler 内部已各自 catch,这里兜住中间件层的异常:
* 非法 JSON、请求体超限、静态资源异常等。所有响应仍走 body.code 约定,
* HTTP 状态保持 200,避免客户端因 413/400 直接拿到非 JSON 文本。
*
* @returns {Function} Koa 中间件
*/
export function createErrorMiddleware() {
return async (ctx, next) => {
try {
await next();
} catch (err) {
// 响应已开始发送时无法再改 body,交给 Koa 默认处理
if (ctx.headerSent) throw err;
const status = Number(err?.status || err?.statusCode) || 500;
if (status >= 400 && status < 500) {
ResponseUtil.error(
ctx,
CLIENT_ERROR_MESSAGES[status] || "请求处理失败",
null,
status
);
return;
}
// 5xx 的详细原因只进日志,不回传堆栈/连接串等内部信息
ResponseUtil.internalError(ctx, err);
}
};
}
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";
// 统一错误出口必须在最外层:body-parser 的 400/413 也要转成约定 JSON
this.app.use(createErrorMiddleware());
// 线上 nginx 只代理 /health 与 /user;保留 /static 供本机访问,
// 同时提供 /health/static,避免独立 /static 请求落到其他服务的默认响应
this.app.use(mount('/health/static', serve(STATIC_DIR)));
this.app.use(mount('/static', serve(STATIC_DIR)));
// Web 后台(escort.huashengtec.com)跨域直连时需要 PATCH,koa-cors 默认不含
this.app.use(cors({ methods: 'GET,HEAD,PUT,POST,DELETE,PATCH' }));
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 };