118 lines
3.0 KiB
JavaScript
118 lines
3.0 KiB
JavaScript
'use strict';
|
|
|
|
const { Controller } = require('egg');
|
|
const { toSuccess, toFailure } = require('../lib/api_response');
|
|
|
|
class GatewayController extends Controller {
|
|
validateParams(params) {
|
|
const required = [ 'method', 'v', 'timestamp' ];
|
|
|
|
for (const field of required) {
|
|
if (!params[field]) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
normalizeResult(result) {
|
|
if (result && typeof result === 'object' && Object.prototype.hasOwnProperty.call(result, 'success') && Object.prototype.hasOwnProperty.call(result, 'code')) {
|
|
if (result.success === false || Number(result.code) <= 0) {
|
|
return {
|
|
httpStatus: 200,
|
|
body: toFailure({
|
|
message: result.message || '请求失败',
|
|
httpStatus: 200,
|
|
code: typeof result.code === 'number' ? result.code : 0,
|
|
data: result.data || null,
|
|
}),
|
|
};
|
|
}
|
|
|
|
return {
|
|
httpStatus: 200,
|
|
body: toSuccess({
|
|
flag: 'success',
|
|
code: result.code,
|
|
message: result.message || 'ok',
|
|
data: result.data || null,
|
|
}),
|
|
};
|
|
}
|
|
|
|
return {
|
|
httpStatus: 200,
|
|
body: toSuccess(result),
|
|
};
|
|
}
|
|
|
|
async internal() {
|
|
const { ctx, service } = this;
|
|
|
|
try {
|
|
const getParams = ctx.query;
|
|
if (!this.validateParams(getParams)) {
|
|
ctx.status = 400;
|
|
ctx.body = toFailure({
|
|
message: '参数缺失或错误: method/v/timestamp',
|
|
httpStatus: 400,
|
|
code: 400,
|
|
});
|
|
ctx.type = 'application/json';
|
|
return;
|
|
}
|
|
|
|
const methods = String(getParams.method).split('.');
|
|
const actionName = methods.pop();
|
|
const className = methods.join('.');
|
|
|
|
let jsonData = '';
|
|
if (ctx.request.rawBody) {
|
|
jsonData = ctx.request.rawBody;
|
|
} else {
|
|
jsonData = await new Promise((resolve, reject) => {
|
|
let data = '';
|
|
ctx.req.on('data', chunk => {
|
|
data += chunk;
|
|
});
|
|
ctx.req.on('end', () => {
|
|
resolve(data);
|
|
});
|
|
ctx.req.on('error', reject);
|
|
});
|
|
}
|
|
|
|
jsonData = jsonData ? String(jsonData) : '';
|
|
if (!jsonData || jsonData.trim() === '') {
|
|
throw new Error('json数据为空');
|
|
}
|
|
|
|
try {
|
|
jsonData = JSON.parse(jsonData);
|
|
} catch (error) {
|
|
throw new Error('json数据解析错误');
|
|
}
|
|
|
|
const result = await service.api.callMethod(className, actionName, jsonData);
|
|
const normalized = this.normalizeResult(result);
|
|
ctx.status = normalized.httpStatus;
|
|
ctx.body = normalized.body;
|
|
ctx.type = 'application/json';
|
|
} catch (error) {
|
|
ctx.status = 500;
|
|
ctx.body = toFailure({
|
|
message: '接口错误: ' + error.message,
|
|
httpStatus: 500,
|
|
code: 500,
|
|
});
|
|
ctx.type = 'application/json';
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = GatewayController; |