Skip to content

Commit 94869c7

Browse files
andveawesleytodd
authored andcommitted
feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729)
1 parent 6ed3439 commit 94869c7

File tree

3 files changed

+34
-4
lines changed

3 files changed

+34
-4
lines changed

History.md

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ unreleased
1111
* Remove unused `depd` dependency
1212
* Add support for `Uint8Array` in `res.send`
1313
* Add support for ETag option in res.sendFile
14+
* Extend res.links() to allow adding multiple links with the same rel
1415
* deps: debug@^4.4.0
1516
* deps: body-parser@^2.1.0
1617
* deps: router@^2.1.0

lib/response.js

+15-4
Original file line numberDiff line numberDiff line change
@@ -80,19 +80,30 @@ res.status = function status(code) {
8080
*
8181
* res.links({
8282
* next: 'http://api.example.com/users?page=2',
83-
* last: 'http://api.example.com/users?page=5'
83+
* last: 'http://api.example.com/users?page=5',
84+
* pages: [
85+
* 'http://api.example.com/users?page=1',
86+
* 'http://api.example.com/users?page=2'
87+
* ]
8488
* });
8589
*
8690
* @param {Object} links
8791
* @return {ServerResponse}
8892
* @public
8993
*/
9094

91-
res.links = function(links){
95+
res.links = function(links) {
9296
var link = this.get('Link') || '';
9397
if (link) link += ', ';
94-
return this.set('Link', link + Object.keys(links).map(function(rel){
95-
return '<' + links[rel] + '>; rel="' + rel + '"';
98+
return this.set('Link', link + Object.keys(links).map(function(rel) {
99+
// Allow multiple links if links[rel] is an array
100+
if (Array.isArray(links[rel])) {
101+
return links[rel].map(function (singleLink) {
102+
return `<${singleLink}>; rel="${rel}"`;
103+
}).join(', ');
104+
} else {
105+
return `<${links[rel]}>; rel="${rel}"`;
106+
}
96107
}).join(', '));
97108
};
98109

test/res.links.js

+18
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,23 @@ describe('res', function(){
4343
.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"')
4444
.expect(200, done);
4545
})
46+
47+
it('should set multiple links for single rel', function (done) {
48+
var app = express();
49+
50+
app.use(function (req, res) {
51+
res.links({
52+
next: 'http://api.example.com/users?page=2',
53+
last: ['http://api.example.com/users?page=5', 'http://api.example.com/users?page=1']
54+
});
55+
56+
res.end();
57+
});
58+
59+
request(app)
60+
.get('/')
61+
.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"')
62+
.expect(200, done);
63+
})
4664
})
4765
})

0 commit comments

Comments
 (0)