Skip to content

Commit

Permalink
Invoke default with same arguments as types in res.format
Browse files Browse the repository at this point in the history
closes #3587
  • Loading branch information
shesek authored and dougwilson committed Mar 26, 2022
1 parent 10b9b50 commit 9482b82
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
1 change: 1 addition & 0 deletions History.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ unreleased
* Allow `options` without `filename` in `res.download`
* Deprecate string and non-integer arguments to `res.status`
* Ignore `Object.prototype` values in settings through `app.set`/`app.get`
* Invoke `default` with same arguments as types in `res.format`
* Support proper 205 responses using `res.send`
* deps: [email protected]
- Remove set content headers that break response
Expand Down
9 changes: 4 additions & 5 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -684,9 +684,8 @@ res.format = function(obj){
var req = this.req;
var next = req.next;

var fn = obj.default;
if (fn) delete obj.default;
var keys = Object.keys(obj);
var keys = Object.keys(obj)
.filter(function (v) { return v !== 'default' })

var key = keys.length > 0
? req.accepts(keys)
Expand All @@ -697,8 +696,8 @@ res.format = function(obj){
if (key) {
this.set('Content-Type', normalizeType(key).value);
obj[key](req, this, next);
} else if (fn) {
fn();
} else if (obj.default) {
obj.default(req, this, next)
} else {
var err = new Error('Not Acceptable');
err.status = err.statusCode = 406;
Expand Down
29 changes: 28 additions & 1 deletion test/res.format.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,12 @@ var app3 = express();
app3.use(function(req, res, next){
res.format({
text: function(){ res.send('hey') },
default: function(){ res.send('default') }
default: function (a, b, c) {
assert(req === a)
assert(res === b)
assert(next === c)
res.send('default')
}
})
});

Expand Down Expand Up @@ -118,6 +123,28 @@ describe('res', function(){
.set('Accept', '*/*')
.expect('hey', done);
})

it('should be able to invoke other formatter', function (done) {
var app = express()

app.use(function (req, res, next) {
res.format({
json: function () { res.send('json') },
default: function () {
res.header('x-default', '1')
this.json()
}
})
})

request(app)
.get('/')
.set('Accept', 'text/plain')
.expect(200)
.expect('x-default', '1')
.expect('json')
.end(done)
})
})

describe('in router', function(){
Expand Down

0 comments on commit 9482b82

Please sign in to comment.