-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.js
78 lines (64 loc) · 1.68 KB
/
index.js
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
/*!
* Express - Contrib - namespace
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var express = require('express')
, join = require('path').join
, HTTPServer = express.HTTPServer
, HTTPSServer = express.HTTPSServer;
/**
* Namespace using the given `path`, providing a callback `fn()`,
* which will be invoked immediately, resetting the namespace to the previous.
*
* @param {String} path
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
exports.namespace = function(path, fn){
(this._ns = this._ns || []).push(path);
fn.call(this);
this._ns.pop();
return this;
};
/**
* Return the current namespace.
*
* @return {String}
* @api public
*/
exports.__defineGetter__('currentNamespace', function(){
return join.apply(this, this._ns).replace(/\/$/, '') || '/';
});
/**
* Proxy HTTP methods to provide namespacing support.
*/
express.router.methods.concat(['del', 'all']).forEach(function(method){
var orig = HTTPServer.prototype[method];
exports[method] = function(){
var args = Array.prototype.slice.call(arguments)
, path = args.shift()
, fn = args.pop()
, self = this;
this.namespace(path, function(){
var curr = this.currentNamespace;
args.forEach(function(fn){
fn.namespace = curr;
orig.call(self, curr, fn);
});
fn.namespace = curr;
orig.call(self, curr, fn);
});
return this;
};
});
// merge
for (var key in exports) {
var desc = Object.getOwnPropertyDescriptor(exports, key);
Object.defineProperty(HTTPServer.prototype, key, desc);
Object.defineProperty(HTTPSServer.prototype, key, desc);
}