Skip to content

Commit

Permalink
feat: Extend res.links() to allow adding multiple links with the same…
Browse files Browse the repository at this point in the history
… rel (closes expressjs#2729) (expressjs#4885)
  • Loading branch information
andvea authored Feb 14, 2025
1 parent 6ed3439 commit caa4f68
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
1 change: 1 addition & 0 deletions History.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ unreleased
* Remove unused `depd` dependency
* Add support for `Uint8Array` in `res.send`
* Add support for ETag option in res.sendFile
* Extend res.links() to allow adding multiple links with the same rel
* deps: debug@^4.4.0
* deps: body-parser@^2.1.0
* deps: router@^2.1.0
Expand Down
19 changes: 15 additions & 4 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,30 @@ res.status = function status(code) {
*
* res.links({
* next: 'http://api.example.com/users?page=2',
* last: 'http://api.example.com/users?page=5'
* last: 'http://api.example.com/users?page=5',
* pages: [
* 'http://api.example.com/users?page=1',
* 'http://api.example.com/users?page=2'
* ]
* });
*
* @param {Object} links
* @return {ServerResponse}
* @public
*/

res.links = function(links){
res.links = function(links) {
var link = this.get('Link') || '';
if (link) link += ', ';
return this.set('Link', link + Object.keys(links).map(function(rel){
return '<' + links[rel] + '>; rel="' + rel + '"';
return this.set('Link', link + Object.keys(links).map(function(rel) {
// Allow multiple links if links[rel] is an array
if (Array.isArray(links[rel])) {
return links[rel].map(function (singleLink) {
return `<${singleLink}>; rel="${rel}"`;
}).join(', ');
} else {
return `<${links[rel]}>; rel="${rel}"`;
}
}).join(', '));
};

Expand Down
18 changes: 18 additions & 0 deletions test/res.links.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,23 @@ describe('res', function(){
.expect('Link', '<http://api.example.com/users?page=2>; rel="next", <http://api.example.com/users?page=5>; rel="last", <http://api.example.com/users?page=1>; rel="prev"')
.expect(200, done);
})

it('should set multiple links for single rel', function (done) {
var app = express();

app.use(function (req, res) {
res.links({
next: 'http://api.example.com/users?page=2',
last: ['http://api.example.com/users?page=5', 'http://api.example.com/users?page=1']
});

res.end();
});

request(app)
.get('/')
.expect('Link', '<http://api.example.com/users?page=2>; rel="next", <http://api.example.com/users?page=5>; rel="last", <http://api.example.com/users?page=1>; rel="last"')
.expect(200, done);
})
})
})

0 comments on commit caa4f68

Please sign in to comment.