更新完善页面
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* v2 API 响应转换中间件
|
||||
*
|
||||
* 用法:在 v2 路由组中挂载此中间件,自动将 v1 风格响应转为 v2 格式
|
||||
* v1: { code: 200, data, message } (HTTP 状态码作业务码)
|
||||
* v2: { code: 0, data, message } (0=成功,非零=错误)
|
||||
*
|
||||
* 路由示例:
|
||||
* router.use('/v2', v2Middleware(), v2Routes)
|
||||
*/
|
||||
|
||||
const { fromV1, SUCCESS, ERROR_MESSAGES } = require('../utils/error-codes')
|
||||
|
||||
function v2ResponseMiddleware() {
|
||||
return async (ctx, next) => {
|
||||
await next()
|
||||
|
||||
// 只处理 JSON 响应
|
||||
if (!ctx.body || typeof ctx.body !== 'object') return
|
||||
|
||||
// 如果已经是 v2 格式(code 为 0 或不在 v1 映射表中),跳过
|
||||
if (ctx.body.code === SUCCESS || ctx.body._v2) return
|
||||
|
||||
// 转换 v1 → v2
|
||||
ctx.body = fromV1(ctx.body)
|
||||
ctx.body._v2 = true
|
||||
|
||||
// 设置 v2 响应头标识
|
||||
ctx.set('X-API-Version', '2')
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { v2ResponseMiddleware }
|
||||
Reference in New Issue
Block a user