UNPKG

1.44 kBJavaScriptView Raw
1
2/**
3 * Module dependencies.
4 */
5
6var debug = require('debug')('koa-mount');
7var compose = require('koa-compose');
8
9/**
10 * Expose `mount()`.
11 */
12
13module.exports = mount;
14
15/**
16 * Mount `app` to `path`, `app`
17 * may be a Koa application or
18 * middleware function.
19 *
20 * @param {String|Application|Function} path, app, or function
21 * @param {Application|Function} [app or function]
22 * @return {Function}
23 * @api public
24 */
25
26function 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 // compose
36 var downstream = app.middleware
37 ? compose(app.middleware)
38 : app;
39
40 return function *(upstream){
41 var prev = this.path;
42
43 // not a match
44 if (0 != this.url.indexOf(path)) return yield upstream;
45
46 // strip the path prefix
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 * Replace `prefix` in `path`.
64 *
65 * @param {String} path
66 * @param {String} prefix
67 * @return {String}
68 * @api private
69 */
70
71function replace(path, prefix) {
72 path = path.replace(prefix, '') || '/';
73 if ('/' != path[0]) path = '/' + path;
74 return path;
75}
\No newline at end of file