Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

res.format(): call default using obj as the context #3587

Merged
merged 1 commit into from
Mar 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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