forked from javascript-tutorial/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmountHandlerMiddleware.js
More file actions
executable file
·54 lines (40 loc) · 1.22 KB
/
mountHandlerMiddleware.js
File metadata and controls
executable file
·54 lines (40 loc) · 1.22 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
var path = require('path');
var mount = require('koa-mount');
// wrap('modulePath')
// is same as
// require('modulePath').middleware,
// but also calls apply/undo upon entering/leaving the middleware
// --> here it does: this.templateDir = handlerModule dirname
module.exports = function(prefix, moduleDir) {
// actually includes router when the middleware is accessed (mount prefix matches)
var lazyRouterMiddleware = require('lib/lazyRouterMiddleware')(path.join(moduleDir, 'router'));
function* wrapMiddleware(next) {
var self = this;
var templateDir = path.join(moduleDir, 'templates');
// before entering middeware
function apply() {
self.templateDir = templateDir;
}
// before leaving middleware
function undo() {
delete self.templateDir;
}
apply();
try {
yield* lazyRouterMiddleware.call(this, function* () {
// when middleware does yield next, undo changes
undo();
try {
yield* next;
} finally {
// ...then apply back, when control goes back after yield next
apply();
}
}());
} finally {
undo();
}
}
// /users/me -> /me
return mount(prefix, wrapMiddleware);
};