forked from javascript-tutorial/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmountHandlerMiddleware.js
More file actions
54 lines (40 loc) · 1.27 KB
/
Copy pathmountHandlerMiddleware.js
File metadata and controls
54 lines (40 loc) · 1.27 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
let path = require('path');
let 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)
let lazyRouterMiddleware = require('./lazyRouterMiddleware')(path.join(moduleDir, 'router'));
let templateDir = path.join(moduleDir, 'templates');
// /users/me -> /me
return mount(prefix, async function wrapMiddleware(ctx, next) {
// before entering middeware
let apply = () => {
// console.log("APPLY", templateDir);
ctx.templateDir = templateDir;
};
// before leaving middleware
let undo = () => {
// console.log("UNDO", templateDir);
delete ctx.templateDir;
};
apply();
try {
await lazyRouterMiddleware(ctx, async function () {
// when middleware does await next, undo changes
undo();
try {
await next();
} finally {
// ...then apply back, when control goes back after await next
apply();
}
});
} finally {
undo();
}
});
};