From 85860587ccfbd1af21bfee0c7428e543ef5cb725 Mon Sep 17 00:00:00 2001 From: "C.T. Lin" Date: Sun, 20 Sep 2015 14:23:42 +0800 Subject: [PATCH] implement ctx.origin --- lib/context.js | 1 + lib/request.js | 13 ++++++++++++- test/request/origin.js | 24 ++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 test/request/origin.js diff --git a/lib/context.js b/lib/context.js index fa13a71..6fe17c3 100644 --- a/lib/context.js +++ b/lib/context.js @@ -176,6 +176,7 @@ delegate(proto, 'request') .access('query') .access('path') .access('url') + .getter('origin') .getter('href') .getter('subdomains') .getter('protocol') diff --git a/lib/request.js b/lib/request.js index 3e0956a..12a92e0 100644 --- a/lib/request.js +++ b/lib/request.js @@ -59,6 +59,17 @@ module.exports = { this.req.url = val; }, + /** + * Get origin of URL. + * + * @return {String} + * @api public + */ + + get origin() { + return this.protocol + '://' + this.host; + }, + /** * Get full request URL. * @@ -71,7 +82,7 @@ module.exports = { if (/^https?:\/\//i.test(this.originalUrl)) { return this.originalUrl; } - return this.protocol + '://' + this.host + this.originalUrl; + return this.origin + this.originalUrl; }, /** diff --git a/test/request/origin.js b/test/request/origin.js new file mode 100644 index 0000000..8c1081f --- /dev/null +++ b/test/request/origin.js @@ -0,0 +1,24 @@ + +var Stream = require('stream'); +var http = require('http'); +var koa = require('../../'); +var context = require('../context'); + +describe('ctx.origin', function(){ + it('should return the origin of url', function(){ + var socket = new Stream.Duplex(); + var req = { + url: '/users/1?next=/dashboard', + headers: { + host: 'localhost' + }, + socket: socket, + __proto__: Stream.Readable.prototype + }; + var ctx = context(req); + ctx.origin.should.equal('http://localhost'); + // change it also work + ctx.url = '/foo/users/1?next=/dashboard'; + ctx.origin.should.equal('http://localhost'); + }) +})