170 lines
4.4 KiB
JavaScript
170 lines
4.4 KiB
JavaScript
const { Controller } = require('egg');
|
|
|
|
class ApiV2Controller extends Controller {
|
|
async index() {
|
|
const { ctx, service } = this;
|
|
ctx.query_count = 1;
|
|
const startTime = Date.now();
|
|
const logData = {
|
|
method: '',
|
|
v: '',
|
|
url: ctx.request.href,
|
|
created_at: new Date(),
|
|
body: '',
|
|
headers: JSON.stringify(ctx.headers),
|
|
result: '',
|
|
use_time: 0,
|
|
auth: '',
|
|
store_id: null,
|
|
};
|
|
|
|
try {
|
|
const getParams = ctx.query;
|
|
logData.method = getParams.method || '';
|
|
logData.v = getParams.v || '';
|
|
// 验证必要参数
|
|
if (!service.system.validateParams(getParams)) {
|
|
const errorMsg = '参数缺失或错误';
|
|
const response = this.errorResponse(errorMsg, 'json');
|
|
logData.result = response;
|
|
service.system.saveLog(logData, startTime);
|
|
ctx.body = response;
|
|
ctx.type = 'application/json';
|
|
return;
|
|
}
|
|
const authHeader = ctx.headers.authorization;
|
|
ctx.device = ctx.headers.device;
|
|
ctx.project = ctx.headers.project;
|
|
|
|
// 处理method参数
|
|
const method = getParams.method;
|
|
const methods = method.split('.');
|
|
const actionName = methods.pop();
|
|
const className = methods
|
|
.map((item, index) =>
|
|
(index === methods.length - 1 ? item : item)
|
|
)
|
|
.join('.');
|
|
|
|
// 获取JSON数据
|
|
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) : '';
|
|
logData.body = jsonData;
|
|
if (!jsonData || jsonData.trim() === '') {
|
|
throw new Error('json数据为空');
|
|
}
|
|
try {
|
|
jsonData = JSON.parse(jsonData);
|
|
} catch (e) {
|
|
throw new Error('json数据解析错误');
|
|
}
|
|
|
|
// 调用扁平 dispatcher 服务
|
|
const { isLog, result } = await service.dispatcher.invoke(
|
|
getParams.method,
|
|
jsonData,
|
|
authHeader,
|
|
ctx
|
|
);
|
|
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
|
if (ctx.user) {
|
|
logData.auth = JSON.stringify(ctx.user);
|
|
logData.store_id = ctx.user.store_id;
|
|
}
|
|
// 保存原来的日志逻辑仍然通过 system.saveLog
|
|
if (isLog) {
|
|
service.system.saveLog(logData, startTime);
|
|
}
|
|
if (result.status && result.status !== 200) {
|
|
// propagate failure message
|
|
ctx.body = result.message ? { message: result.message } : result.data;
|
|
} else {
|
|
ctx.body = result.data;
|
|
}
|
|
ctx.type = 'application/json';
|
|
ctx.status = result.status || 200;
|
|
} catch (error) {
|
|
ctx.status = 500;
|
|
console.log(error);
|
|
const response = this.errorResponse('接口错误: ' + error.message, 'json');
|
|
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
|
service.system.saveLog(logData, startTime);
|
|
ctx.body = response;
|
|
ctx.type = 'application/json';
|
|
}
|
|
}
|
|
|
|
validateParams(params) {
|
|
const required = [ 'method', 'v', 'format', 'timestamp' ];
|
|
|
|
for (const field of required) {
|
|
if (!params[field]) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
errorResponse(message, format = 'json') {
|
|
const timestamp = Math.floor(Date.now() / 1000);
|
|
|
|
if (format.toLowerCase() === 'xml') {
|
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
<response>
|
|
<flag>failure</flag>
|
|
<code>0</code>
|
|
<message>${this.escapeXml(message)}</message>
|
|
</response>`;
|
|
}
|
|
|
|
return {
|
|
flag: false,
|
|
message,
|
|
code: 0,
|
|
timestamp,
|
|
};
|
|
}
|
|
|
|
escapeXml(unsafe) {
|
|
if (!unsafe) return '';
|
|
return unsafe.replace(/[<>&'\"]/g, c => {
|
|
switch (c) {
|
|
case '<':
|
|
return '<';
|
|
case '>':
|
|
return '>';
|
|
case '&':
|
|
return '&';
|
|
case "'":
|
|
return ''';
|
|
case '"':
|
|
return '"';
|
|
default:
|
|
return c;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = ApiV2Controller;
|