From caa4f68ee8d32474676fa29cc2086dcc1d62208b Mon Sep 17 00:00:00 2001 From: Andrea Polverino <36574883+andvea@users.noreply.github.com> Date: Fri, 14 Feb 2025 17:20:53 +0100 Subject: [PATCH] feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729) (#4885) --- History.md | 1 + lib/response.js | 19 +++++++++++++++---- test/res.links.js | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/History.md b/History.md index 021315c5..98cfb14c 100644 --- a/History.md +++ b/History.md @@ -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 diff --git a/lib/response.js b/lib/response.js index b1dfcb23..9362d0ed 100644 --- a/lib/response.js +++ b/lib/response.js @@ -80,7 +80,11 @@ 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 @@ -88,11 +92,18 @@ res.status = function status(code) { * @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(', ')); }; diff --git a/test/res.links.js b/test/res.links.js index 240b7fcf..40665fd5 100644 --- a/test/res.links.js +++ b/test/res.links.js @@ -43,5 +43,23 @@ describe('res', function(){ .expect('Link', '; rel="next", ; rel="last", ; 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', '; rel="next", ; rel="last", ; rel="last"') + .expect(200, done); + }) }) })