app.context: extend the context with your own properties

This commit is contained in:
Jonathan Ong 2013-08-17 15:36:51 -07:00
parent cdba6f87ed
commit 978f581099
4 changed files with 160 additions and 39 deletions

View file

@ -6,7 +6,7 @@
var debug = require('debug')('koa:app'); var debug = require('debug')('koa:app');
var Emitter = require('events').EventEmitter; var Emitter = require('events').EventEmitter;
var compose = require('koa-compose'); var compose = require('koa-compose');
var Context = require('./context'); var context = require('./context');
var Stream = require('stream'); var Stream = require('stream');
var http = require('http'); var http = require('http');
var co = require('co'); var co = require('co');
@ -37,6 +37,12 @@ function Application() {
this.poweredBy = true; this.poweredBy = true;
this.jsonSpaces = 2; this.jsonSpaces = 2;
this.middleware = []; this.middleware = [];
this._Context = function Context(app, req, res){
this.app = app;
this.req = req;
this.res = res;
}
this.context(context);
} }
/** /**
@ -74,6 +80,35 @@ app.use = function(fn){
return this; return this;
}; };
/**
* Mixin an app's context with your own object.
*
* app.context({
* get something(){
* return 'hi';
* },
* set something(val){
* this._something = val;
* },
* render: function(){
* this.body = '<html></html>';
* }
* })
*
* @param {Object} obj
* @return {Application} self
* @api public
*/
app.context = function(obj){
var ctx = this._Context.prototype;
Object.getOwnPropertyNames(obj).forEach(function(name){
var descriptor = Object.getOwnPropertyDescriptor(obj, name);
Object.defineProperty(ctx, name, descriptor);
});
return this;
};
/** /**
* Return a request handler callback * Return a request handler callback
* for node's native htto server. * for node's native htto server.
@ -88,7 +123,7 @@ app.callback = function(){
var self = this; var self = this;
return function(req, res){ return function(req, res){
var ctx = new Context(self, req, res); var ctx = new self._Context(self, req, res);
function done(err) { function done(err) {
if (err) ctx.error(err); if (err) ctx.error(err);
@ -126,7 +161,7 @@ function respond(next){
this.set('Content-Type', 'text/plain'); this.set('Content-Type', 'text/plain');
body = http.STATUS_CODES[this.status]; body = http.STATUS_CODES[this.status];
} }
// Buffer body // Buffer body
if (Buffer.isBuffer(body)) { if (Buffer.isBuffer(body)) {
var ct = this.responseHeader['content-type']; var ct = this.responseHeader['content-type'];
@ -151,7 +186,7 @@ function respond(next){
if (head) return res.end(); if (head) return res.end();
return body.pipe(res); return body.pipe(res);
} }
// body: json // body: json
body = JSON.stringify(body, null, this.app.jsonSpaces); body = JSON.stringify(body, null, this.app.jsonSpaces);
this.set('Content-Length', body.length); this.set('Content-Length', body.length);

View file

@ -16,35 +16,12 @@ var url = require('url');
var qs = require('qs'); var qs = require('qs');
var parse = url.parse; var parse = url.parse;
var stringify = url.format; var stringify = url.format;
var ctx = Context.prototype;
/**
* Expose `Context`.
*/
module.exports = Context;
/**
* Initialize a new Context with raw node
* request and response objects.
*
* @param {Application} app
* @param {Request} req
* @param {Request} res
* @api public
*/
function Context(app, req, res) {
this.app = app;
this.req = req;
this.res = res;
}
/** /**
* Prototype. * Prototype.
*/ */
Context.prototype = { module.exports = {
/** /**
* Return request header. * Return request header.
@ -509,7 +486,7 @@ Context.prototype = {
/** /**
* Return accepted encodings. * Return accepted encodings.
* *
* Given `Accept-Encoding: gzip, deflate` * Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned: * an array sorted by quality is returned:
* *
* ['gzip', 'deflate'] * ['gzip', 'deflate']
@ -526,7 +503,7 @@ Context.prototype = {
/** /**
* Return accepted charsets. * Return accepted charsets.
* *
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned: * an array sorted by quality is returned:
* *
* ['utf-8', 'utf-7', 'iso-8859-1'] * ['utf-8', 'utf-7', 'iso-8859-1']
@ -543,7 +520,7 @@ Context.prototype = {
/** /**
* Return accepted languages. * Return accepted languages.
* *
* Given `Accept-Language: en;q=0.8, es, pt` * Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned: * an array sorted by quality is returned:
* *
* ['es', 'pt', 'en'] * ['es', 'pt', 'en']
@ -560,7 +537,7 @@ Context.prototype = {
/** /**
* Return accepted media types. * Return accepted media types.
* *
* Given `Accept: application/*;q=0.2, image/jpeg;q=0.8, text/html` * Given `Accept: application/*;q=0.2, image/jpeg;q=0.8, text/html`
* an array sorted by quality is returned: * an array sorted by quality is returned:
* *
* ['text/html', 'image/jpeg', 'application/*'] * ['text/html', 'image/jpeg', 'application/*']
@ -644,7 +621,7 @@ Context.prototype = {
// extension given // extension given
if (!~type.indexOf('/')) type = mime.lookup(type); if (!~type.indexOf('/')) type = mime.lookup(type);
// type or subtype match // type or subtype match
if (~type.indexOf('*')) { if (~type.indexOf('*')) {
type = type.split('/'); type = type.split('/');
@ -827,7 +804,7 @@ Context.prototype = {
/** /**
* Inspect implementation. * Inspect implementation.
* *
* TODO: add tests * TODO: add tests
* *
* @return {Object} * @return {Object}

View file

@ -252,4 +252,105 @@ describe('app.respond', function(){
.end(done); .end(done);
}) })
}) })
})
describe('app.context', function(){
it('should merge regular object properties', function(done){
var app = koa();
app.context({
a: 1,
b: 2
});
app.use(function(next){
return function *(){
this.a.should.equal(1);
this.b.should.equal(2);
this.status = 204;
}
});
var server = http.createServer(app.callback());
request(server)
.get('/')
.expect(204)
.end(done);
})
it('should merge accessor properties', function(done){
var app = koa();
app.context({
get something() {
return this._something || 'hi';
},
set something(value) {
this._something = value;
}
});
app.use(function(next){
return function *(){
this.something.should.equal('hi');
this.something = 'hello';
this.something.should.equal('hello');
this.status = 204;
}
});
var server = http.createServer(app.callback());
request(server)
.get('/')
.expect(204)
.end(done);
})
it('should merge multiple objects', function(done){
var app = koa();
app.context({
a: 1
});
app.context({
b: 2
});
app.use(function(next){
return function *(){
this.a.should.equal(1);
this.b.should.equal(2);
this.status = 204;
}
});
var server = http.createServer(app.callback());
request(server)
.get('/')
.expect(204)
.end(done);
})
it('should not butcher the original prototype', function(done){
var app1 = koa();
var app2 = koa();
app1.context({
a: 1
});
app2.use(function(next){
return function *(){
assert.equal(this.a, undefined);
this.status = 204;
}
});
var server = http.createServer(app2.callback());
request(server)
.get('/')
.expect(204)
.end(done);
})
}) })

View file

@ -1,9 +1,17 @@
var Context = require('../lib/context'); var _context = require('../lib/context');
var assert = require('assert'); var assert = require('assert');
var koa = require('..'); var koa = require('..');
var fs = require('fs'); var fs = require('fs');
function Context(app, req, res) {
this.app = app;
this.req = req;
this.res = res;
}
Context.prototype = _context;
function context(req, res) { function context(req, res) {
req = req || { headers: {} }; req = req || { headers: {} };
res = res || { _headers: {} }; res = res || { _headers: {} };
@ -19,7 +27,7 @@ describe('ctx.length', function(){
ctx.header['content-length'] = '120'; ctx.header['content-length'] = '120';
ctx.length.should.equal(120); ctx.length.should.equal(120);
}) })
}) })
}) })
describe('ctx.responseLength', function(){ describe('ctx.responseLength', function(){
@ -50,7 +58,7 @@ describe('ctx.responseLength', function(){
describe('and .body is not', function(){ describe('and .body is not', function(){
it('should return undefined', function(){ it('should return undefined', function(){
var ctx = context(); var ctx = context();
assert(null == ctx.responseLength); assert(null == ctx.responseLength);
}) })
}) })
}) })
@ -454,7 +462,7 @@ describe('ctx.query', function(){
describe('when missing', function(){ describe('when missing', function(){
it('should return an empty object', function(){ it('should return an empty object', function(){
var ctx = context({ url: '/' }); var ctx = context({ url: '/' });
ctx.query.should.eql({}); ctx.query.should.eql({});
}) })
}) })
@ -521,7 +529,7 @@ describe('ctx.is(type)', function(){
it('should ignore params', function(){ it('should ignore params', function(){
var ctx = context(); var ctx = context();
ctx.header['content-type'] = 'text/html; charset=utf-8'; ctx.header['content-type'] = 'text/html; charset=utf-8';
ctx.is('text/*').should.be.true; ctx.is('text/*').should.be.true;
}) })
describe('given a mime', function(){ describe('given a mime', function(){