Permalink
Browse files

Add subdomain offset setting

Add a setting "subdomain offset" for the app, which can be used to
change the behavior of req.subdomains. This is useful when our "base"
domain contains more than two parts, e.g. example.co.uk, and also
when we are running locally with domains like xxx.local.

The default behavior is still to return all but the last two parts.
  • Loading branch information...
1 parent 8beb1f2 commit ba00e236302e9f74d0d35c1dd8522580076cab9b @gmethvin gmethvin committed Jan 20, 2013
Showing with 61 additions and 6 deletions.
  1. +11 −6 lib/request.js
  2. +50 −0 test/req.subdomains.js
View
@@ -401,18 +401,23 @@ req.__defineGetter__('auth', function(){
/**
* Return subdomains as an array.
*
- * For example "tobi.ferrets.example.com"
- * would provide `["ferrets", "tobi"]`.
+ * Subdomains are the dot-separated parts of the host before the main domain of
+ * the app. By default, the domain of the app is assumed to be the last two
+ * parts of the host. This can be changed by setting "subdomain offset".
+ *
+ * For example, if the domain is "tobi.ferrets.example.com":
+ * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
+ * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
*
* @return {Array}
* @api public
*/
req.__defineGetter__('subdomains', function(){
- return this.get('Host')
- .split('.')
- .slice(0, -2)
- .reverse();
+ var offset = this.app.get('subdomain offset');
+ if (offset == null) offset = 2;
+
+ return this.get('Host').split('.').reverse().slice(offset);
});
/**
View
@@ -33,5 +33,55 @@ describe('req', function(){
.expect('[]', done);
})
})
+
+ describe('when subdomain offset is set', function(){
+ describe('when subdomain offset is zero', function(){
+ it('should return an array with the whole domain', function(done){
+ var app = express();
+ app.set('subdomain offset', 0);
+
+ app.use(function(req, res){
+ res.send(req.subdomains);
+ });
+
+ request(app)
+ .get('/')
+ .set('Host', 'tobi.ferrets.sub.example.com')
+ .expect('["com","example","sub","ferrets","tobi"]', done);
+ })
+ })
+
+ describe('when present', function(){
+ it('should return an array', function(done){
+ var app = express();
+ app.set('subdomain offset', 3);
+
+ app.use(function(req, res){
+ res.send(req.subdomains);
+ });
+
+ request(app)
+ .get('/')
+ .set('Host', 'tobi.ferrets.sub.example.com')
+ .expect('["ferrets","tobi"]', done);
+ })
+ })
+
+ describe('otherwise', function(){
+ it('should return an empty array', function(done){
+ var app = express();
+ app.set('subdomain offset', 3);
+
+ app.use(function(req, res){
+ res.send(req.subdomains);
+ });
+
+ request(app)
+ .get('/')
+ .set('Host', 'sub.example.com')
+ .expect('[]', done);
+ })
+ })
+ })
})
})

0 comments on commit ba00e23

Please sign in to comment.