-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathhandlerService.ts
More file actions
247 lines (222 loc) · 6.76 KB
/
Copy pathhandlerService.ts
File metadata and controls
247 lines (222 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import * as fs from 'fs';
import * as utils from '../../util/utils';
import * as Loader from 'pinus-loader';
import * as pathUtil from '../../util/pathUtil';
import { getLogger } from 'pinus-logger';
import { Application } from '../../application';
import { Session, FrontendSession } from './sessionService';
import { RouteRecord, ServerInfo } from '../../util/constants';
import { BackendSession } from './backendSessionService';
let logger = getLogger('pinus', __filename);
let forwardLogger = getLogger('forward-log', __filename);
export interface HandlerServiceOptions
{
reloadHandlers ?: boolean;
enableForwardLog ?: boolean;
handlersPaths ?: string[];
}
export type HandlerCallback = (err : Error , response ?: any)=>void;
export type HandlerMethod = (msg : any , session : FrontendSession | BackendSession)=>Promise<any>;
export type Handler = {[method : string] : HandlerMethod};
export type Handlers = {[handler : string] : Handler};
export type HandlerMap = {[serverType : string] : Handlers};
/**
* Handler service.
* Dispatch request to the relactive handler.
*
* @param {Object} app current application context
*/
export class HandlerService
{
app: Application;
handlerMap : HandlerMap = {};
handlerPaths : {[serverType:string]:Set<string>} = {};
enableForwardLog: boolean;
constructor(app : Application, opts : HandlerServiceOptions)
{
this.app = app;
if (!!opts.reloadHandlers)
{
watchHandlers(app, this.handlerMap);
}
this.enableForwardLog = opts.enableForwardLog || false;
// 添加默认路径到ServerInfo中
let info = app.getCurrentServer()
let handlerPath = pathUtil.getHandlerPath(app.getBase(), info.serverType);
info.handlerPaths = [];
if(handlerPath)
{
info.handlerPaths.push(handlerPath);
}
// 添加插件中的handler到ServerInfo中
for(let plugin of app.usedPlugins)
{
if(plugin.handlerPath)
{
info.handlerPaths.push(plugin.handlerPath);
}
}
// 添加一台服务器
this.addServer(info);
};
name = 'handler';
/**
* Handler the request.
*/
handle(routeRecord : RouteRecord, msg : any, session : FrontendSession | BackendSession, cb : HandlerCallback)
{
// the request should be processed by current server
let handler = this.getHandler(routeRecord);
if (!handler)
{
logger.error('[handleManager]: fail to find handler for %j', routeRecord.route);
utils.invokeCallback(cb, new Error('fail to find handler for ' + routeRecord.route));
return;
}
let start = Date.now();
let self = this;
let callback = function (err?: any, resp?: any, opts?: any)
{
if (self.enableForwardLog)
{
let log = {
route: routeRecord.route,
args: msg,
time: utils.format(new Date(start)),
timeUsed: Date.now() - start
};
forwardLogger.info(JSON.stringify(log));
}
// resp = getResp(arguments);
utils.invokeCallback(cb, err, resp, opts);
}
let method = routeRecord.method;
if (!Array.isArray(msg))
{
handler[method](msg, session).then((resp) =>
{
callback(null, resp);
}, (reason) =>
{
callback(reason);
});
} else
{
msg.push(session);
handler[method].apply(handler, msg).then((resp : any) =>
{
callback(null, resp);
}, (reason : any) =>
{
callback(reason);
});
}
return;
};
/**
* Get handler instance by routeRecord.
*
* @param {Object} handlers handler map
* @param {Object} routeRecord route record parsed from route string
* @return {Object} handler instance if any matchs or null for match fail
*/
getHandler(routeRecord : RouteRecord)
{
let serverType = routeRecord.serverType;
if (!this.handlerMap[serverType])
{
this.loadHandlers(serverType);
}
let handlers = this.handlerMap[serverType] || {};
let handler = handlers[routeRecord.handler];
if (!handler)
{
logger.warn('could not find handler for routeRecord: %j', routeRecord);
return null;
}
if (typeof handler[routeRecord.method] !== 'function')
{
logger.warn('could not find the method %s in handler: %s', routeRecord.method, routeRecord.handler);
return null;
}
return handler;
};
private parseHandler(serverType:string , handlerPath:string)
{
let modules = Loader.load(handlerPath, this.app, false) as Handlers;
for(let name in modules)
{
let targetHandlers = this.handlerMap[serverType];
if(!targetHandlers)
{
targetHandlers = {};
this.handlerMap[serverType] = targetHandlers;
}
targetHandlers[name] = modules[name];
}
}
private addServer(serverInfo : ServerInfo)
{
let targetPaths = this.handlerPaths[serverInfo.serverType];
if(!targetPaths)
{
targetPaths = new Set<string>();
this.handlerPaths[serverInfo.serverType] = targetPaths;
}
for(let path of serverInfo.handlerPaths)
{
targetPaths.add(path);
}
}
/**
* Load handlers from current application
*/
private loadHandlers(serverType: string)
{
let paths = this.handlerPaths[serverType];
for(let path of paths)
{
this.parseHandler(serverType , path);
}
};
}
let watchHandlers = function (app: Application, handlerMap: HandlerMap)
{
let p = pathUtil.getHandlerPath(app.getBase(), app.serverType);
if (!!p)
{
fs.watch(p, function (event, name)
{
if (event === 'change')
{
handlerMap[app.serverType] = Loader.load(p, app, true);
}
});
}
};
let getResp = function (args: any)
{
let len = args.length;
if (len == 1)
{
return [];
}
if (len == 2)
{
return [args[1]];
}
if (len == 3)
{
return [args[1], args[2]];
}
if (len == 4)
{
return [args[1], args[2], args[3]];
}
let r = new Array(len);
for (let i = 1; i < len; i++)
{
r[i] = args[i];
}
return r;
}