Skip to content

Commit

Permalink
response.redirect: extract special-cased back
Browse files Browse the repository at this point in the history
  • Loading branch information
fl0w committed Feb 14, 2018
1 parent 916f914 commit cad890c
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
1 change: 1 addition & 0 deletions lib/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ delegate(proto, 'response')
.method('set')
.method('append')
.method('flushHeaders')
.method('back')
.access('status')
.access('message')
.access('body')
Expand Down
26 changes: 24 additions & 2 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const assert = require('assert');
const extname = require('path').extname;
const vary = require('vary');
const only = require('only');
const deprecate = require('depd')('koa');

/**
* Prototype.
Expand Down Expand Up @@ -252,13 +253,16 @@ module.exports = {
* this.redirect('http://google.com');
*
* @param {String} url
* @param {String} [alt]
* @api public
*/

redirect(url, alt) {
// location
if ('back' == url) url = this.ctx.get('Referrer') || alt || '/';
if ('back' == url) {
deprecate('Special-cased string "back" through redirect will be removed in v3,' +
'consider migrating usage to ctx.back() instead.');
url = this.ctx.get('Referrer') || alt || '/';
}
this.set('Location', url);

// status
Expand All @@ -277,6 +281,24 @@ module.exports = {
this.body = `Redirecting to ${url}.`;
},

/**
* Perform a special-cased "back" to provide Referrer support.
* When Referrer is not present, `alt` or "/" is used.
*
* Examples:
*
* ctx.back()
* ctx.back('/index.html')
*
* @param {String} [alt]
* @api public
*/

back(alt) {
const url = this.ctx.get('Referrer') || alt || '/';
this.redirect(url);
},

/**
* Set Content-Disposition header to "attachment" with optional `filename`.
*
Expand Down
33 changes: 33 additions & 0 deletions test/response/back.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

'use strict';

const assert = require('assert');
const context = require('../helpers/context');

describe('ctx.back([alt])', () => {
it('should redirect to Referrer', () => {
const ctx = context();
ctx.req.headers.referrer = '/login';
ctx.back();
assert.equal(ctx.response.header.location, '/login');
});

it('should redirect to Referer', () => {
const ctx = context();
ctx.req.headers.referer = '/login';
ctx.back();
assert.equal(ctx.response.header.location, '/login');
});

it('should default to alt', () => {
const ctx = context();
ctx.back('/index.html');
assert.equal(ctx.response.header.location, '/index.html');
});

it('should default redirect to /', () => {
const ctx = context();
ctx.back();
assert.equal(ctx.response.header.location, '/');
});
});

0 comments on commit cad890c

Please sign in to comment.