83 lines
2.6 KiB
JavaScript
83 lines
2.6 KiB
JavaScript
'use strict';
|
|
|
|
const Service = require('egg').Service;
|
|
|
|
class DispatcherService extends Service {
|
|
constructor(ctx) {
|
|
super(ctx);
|
|
// postpone building map until needed
|
|
this.methodMap = null;
|
|
}
|
|
|
|
// recursively walk through object to collect functions
|
|
buildMap(obj, prefix = '') {
|
|
// avoid expensive or dangerous walk when running tests
|
|
if (process.env.NODE_ENV === 'test') return {};
|
|
const map = {};
|
|
Object.keys(obj).forEach(key => {
|
|
let value;
|
|
try {
|
|
value = obj[key];
|
|
} catch (err) {
|
|
// skip getters that throw
|
|
return;
|
|
}
|
|
const path = prefix ? `${prefix}.${key}` : key;
|
|
if (typeof value === 'function') {
|
|
map[path] = value.bind(obj);
|
|
} else if (value && typeof value === 'object') {
|
|
Object.assign(map, this.buildMap(value, path));
|
|
}
|
|
});
|
|
return map;
|
|
}
|
|
|
|
getMethodMap() {
|
|
if (!this.methodMap) {
|
|
this.methodMap = this.buildMap(this.ctx.service.systemMethods || {});
|
|
}
|
|
return this.methodMap;
|
|
}
|
|
|
|
async invoke(method, data, authHeader, ctx) {
|
|
// debug output: show incoming request method and payload size
|
|
console.debug('[dispatcher] invoke method', method, 'data size',
|
|
data ? JSON.stringify(data).length : 0);
|
|
|
|
const fn = this.getMethodMap()[method];
|
|
if (!fn) {
|
|
console.error('[dispatcher] method not found in map:', method);
|
|
throw new Error(`方法 ${method} 不存在 (检查 systemMethods 目录或拼写)`);
|
|
}
|
|
// perform global auth/log check using original service API
|
|
// we rely on the service instance to provide checkAuth, so find owning service
|
|
const parts = method.split('.');
|
|
const action = parts.pop();
|
|
const servicePath = parts.join('.');
|
|
|
|
// resolve the service instance again (should be same as that bound earlier)
|
|
let svc = ctx.service.systemMethods;
|
|
parts.forEach(p => {
|
|
svc = svc && svc[p];
|
|
});
|
|
|
|
if (!svc) {
|
|
console.error('[dispatcher] service instance not found for path', servicePath);
|
|
throw new Error(`服务 ${servicePath} 不存在`);
|
|
}
|
|
|
|
const authPass = await svc.checkAuth(servicePath, action, authHeader);
|
|
const isLog = authPass.isLog;
|
|
if (authPass.status !== 200) {
|
|
console.debug('[dispatcher] auth failed', authPass);
|
|
return { isLog, result: { status: authPass.status, message: authPass.message } };
|
|
}
|
|
|
|
const resultData = await fn(data);
|
|
console.debug('[dispatcher] method executed successfully', method);
|
|
return { isLog, result: { status: 200, data: resultData } };
|
|
}
|
|
}
|
|
|
|
module.exports = DispatcherService;
|