109 lines
3.1 KiB
JavaScript
109 lines
3.1 KiB
JavaScript
'use strict';
|
|
|
|
const Service = require('egg').Service;
|
|
const { XMLParser } = require('fast-xml-parser');
|
|
|
|
class systemService extends Service {
|
|
async callMethod(className, actionName, requestData, authHeader) {
|
|
try {
|
|
|
|
|
|
// 构建服务类路径
|
|
const servicePath = `${className}`;
|
|
const classs = servicePath.split('.');
|
|
let systemMethods = this.ctx.service.systemMethods;
|
|
for (let i = 0; i < classs.length; i++) {
|
|
const className = classs[i];
|
|
systemMethods = systemMethods[className];
|
|
}
|
|
// 检查服务是否存在
|
|
if (!systemMethods) {
|
|
throw new Error(`服务 ${servicePath} 不存在`);
|
|
}else{
|
|
console.log(`调用服务: ${servicePath}, 方法: ${actionName}`);
|
|
}
|
|
const serviceInstance = systemMethods;
|
|
|
|
// 检查方法是否存在
|
|
if (typeof serviceInstance[actionName] !== 'function') {
|
|
throw new Error(`方法 ${actionName} 不存在`);
|
|
}
|
|
const result = {
|
|
message: '',
|
|
status: 401,
|
|
};
|
|
// 调用方法
|
|
const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader);
|
|
const isLog = authPass.isLog;
|
|
if (authPass.status == 200) {
|
|
result.data = await serviceInstance[actionName](requestData);
|
|
console.log(result.data);
|
|
result.status = 200;
|
|
|
|
} else {
|
|
result.message = authPass.message;
|
|
result.status = authPass.status;
|
|
}
|
|
return { isLog, result };
|
|
|
|
} catch (error) {
|
|
throw error;
|
|
}
|
|
}
|
|
validateParams(params) {
|
|
const required = [ 'method', 'v', 'timestamp' ];
|
|
|
|
for (const field of required) {
|
|
if (!params[field]) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// 验证method格式
|
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
async saveLog(logData, startTime) {
|
|
const {
|
|
ctx,
|
|
} = this;
|
|
|
|
try {
|
|
// 限制日志内容长度
|
|
if (logData.body && logData.body.length > 65535) {
|
|
logData.body = logData.body.substring(0, 65535);
|
|
}
|
|
|
|
if (logData.result && logData.result.length > 65535) {
|
|
logData.result = logData.result.substring(0, 65535);
|
|
}
|
|
|
|
logData.use_time = Date.now() - startTime;
|
|
|
|
// 使用 egg-mysql 保存日志到数据库
|
|
const result = await ctx.app.mysql.get('wms').insert('wms_system_log', {
|
|
method: logData.method || '',
|
|
v: logData.v || '',
|
|
url: logData.url || '',
|
|
headers: logData.headers || '',
|
|
auth: logData.auth || '',
|
|
created_at: ctx.app.mysql.get('wms').literals.now,
|
|
body: logData.body || '',
|
|
result: logData.result || '',
|
|
use_time: logData.use_time || 0,
|
|
store_id: logData.store_id || null,
|
|
device: ctx.header.platform,
|
|
});
|
|
return result;
|
|
} catch (error) {
|
|
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
|
|
// 可以选择记录到文件日志作为备用
|
|
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
|
}
|
|
}
|
|
}
|
|
module.exports = systemService;
|