Skip to content

Commit

Permalink
Add support for custom statuses
Browse files Browse the repository at this point in the history
  • Loading branch information
LukeBousfield committed Jan 5, 2018
1 parent 6baa411 commit 8966c35
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
13 changes: 13 additions & 0 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ module.exports = class Application extends Emitter {
this.context = Object.create(context);
this.request = Object.create(request);
this.response = Object.create(response);
this.customStatuses = {};
}

/**
* Add custom status code
* @param {Number} code
* @param {String} description
* @api public
*/

addStatus(code, description) {
this.customStatuses[code] = description;
}

/**
Expand Down Expand Up @@ -166,6 +178,7 @@ module.exports = class Application extends Emitter {
request.ctx = response.ctx = context;
request.response = response;
response.request = request;
response.customStatuses = this.customStatuses;
context.originalUrl = request.originalUrl = req.url;
context.cookies = new Cookies(req, res, {
keys: this.keys,
Expand Down
4 changes: 2 additions & 2 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ module.exports = {

set status(code) {
assert('number' == typeof code, 'status code must be a number');
assert(statuses[code], `invalid status code: ${code}`);
assert(statuses[code] || this.customStatuses[code], `invalid status code: ${code}`);
assert(!this.res.headersSent, 'headers have already been sent');
this._explicitStatus = true;
this.res.statusCode = code;
if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code];
if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code] || this.customStatuses[code];
if (this.body && statuses.empty[code]) this.body = null;
},

Expand Down
2 changes: 1 addition & 1 deletion test/application/respond.js
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ describe('app.respond', () => {
describe('with custom status=700', () => {
it('should respond with the associated status message', async () => {
const app = new Koa();
statuses['700'] = 'custom status';
app.addStatus(700, 'custom status');

app.use(ctx => {
ctx.status = 700;
Expand Down

0 comments on commit 8966c35

Please sign in to comment.