57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
'use strict';
|
|
|
|
const { Controller } = require('egg');
|
|
const { toSuccess, toFailure } = require('../lib/api_response');
|
|
|
|
class OpenapiController extends Controller {
|
|
/**
|
|
* 输出 openapi 统一失败响应。
|
|
* @param {number} httpStatus HTTP 状态码。
|
|
* @param {string} message 错误消息。
|
|
* @param {number} [code=httpStatus] 业务错误码。
|
|
* @return {void} 无返回值。
|
|
*/
|
|
writeFailureResponse(httpStatus, message, code = httpStatus) {
|
|
const { ctx } = this;
|
|
ctx.status = httpStatus;
|
|
ctx.body = toFailure({
|
|
message,
|
|
httpStatus,
|
|
code,
|
|
});
|
|
ctx.type = 'application/json';
|
|
}
|
|
|
|
/**
|
|
* OpenAPI 统一入口,仅负责转发到 openapi service 并输出标准响应。
|
|
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
|
|
*/
|
|
async index() {
|
|
const { ctx } = this;
|
|
|
|
try {
|
|
const result = await ctx.service.openapi.processRequest();
|
|
if (result.ok) {
|
|
ctx.status = Number(result.httpStatus) || 200;
|
|
ctx.body = toSuccess(result.data, result.message || 'ok');
|
|
ctx.type = 'application/json';
|
|
return;
|
|
}
|
|
|
|
this.writeFailureResponse(
|
|
Number(result.httpStatus) || 500,
|
|
String(result.message || '请求失败'),
|
|
Number(result.code) || Number(result.httpStatus) || 500
|
|
);
|
|
ctx.type = 'application/json';
|
|
return;
|
|
} catch (error) {
|
|
const message = String(error && error.message || '请求失败');
|
|
this.writeFailureResponse(500, `接口错误: ${message}`, 500);
|
|
ctx.type = 'application/json';
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = OpenapiController;
|