1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | var debug = require('debug')('koa-mount');
|
7 | var compose = require('koa-compose');
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | module.exports = mount;
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function mount(path, app) {
|
27 | if ('string' != typeof path) {
|
28 | app = path;
|
29 | path = '/';
|
30 | }
|
31 |
|
32 | var name = app.name || 'unnamed';
|
33 | debug('mount %s %s', path, name);
|
34 |
|
35 |
|
36 | var downstream = app.middleware
|
37 | ? compose(app.middleware)
|
38 | : app;
|
39 |
|
40 | return function *(upstream){
|
41 | var prev = this.path;
|
42 |
|
43 |
|
44 | if (0 != this.url.indexOf(path)) return yield upstream;
|
45 |
|
46 |
|
47 | var newPath = replace(this.path, path);
|
48 | this.path = newPath;
|
49 | debug('enter %s -> %s', prev, this.path);
|
50 |
|
51 | yield downstream.call(this, function *(){
|
52 | this.path = prev;
|
53 | yield upstream;
|
54 | this.path = newPath;
|
55 | }.call(this));
|
56 |
|
57 | debug('leave %s -> %s', prev, this.path);
|
58 | this.path = prev;
|
59 | }
|
60 | }
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | function replace(path, prefix) {
|
72 | path = path.replace(prefix, '') || '/';
|
73 | if ('/' != path[0]) path = '/' + path;
|
74 | return path;
|
75 | } |
\ | No newline at end of file |