diff --git a/lib/response.js b/lib/response.js index 641704b04a..4411e19d2d 100644 --- a/lib/response.js +++ b/lib/response.js @@ -70,17 +70,46 @@ res.status = function status(code) { * last: 'http://api.example.com/users?page=5' * }); * - * @param {Object} links + * or + * + * res.links([ + * { + * href: 'http://api.example.com/users?page=2', + * rel: 'next', + * title: 'next chapter', + * type: 'text/plain;charset=UTF-8' + * }, + * { + * href: 'http://api.example.com/users?page=5', + * rel: 'last', + * title: 'the grand finale', + * type: 'video/webm' + * } + * ]); + * @param {Object|Array} links * @return {ServerResponse} * @public */ -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 + '"'; - }).join(', ')); +res.links = function (links) { + var link = this.get('Link') || ''; + if (link) link += ', '; + if (Array.isArray(links)) { + link += Object.keys(links).map(function (i) { + return Object.keys(links[i]).map(function (item) { + if (item === 'href') + return '<' + links[i][item] + '>'; + else + return item + '="' + links[i][item] + '"'; + }).join('; ') + }).join(', ') + } + else { + link += Object.keys(links).map(function (rel) { + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ') + } + return this.set('Link', link); }; /** diff --git a/test/res.links.js b/test/res.links.js index 36630c9ccc..15271faf98 100644 --- a/test/res.links.js +++ b/test/res.links.js @@ -42,5 +42,33 @@ describe('res', function(){ .expect('Link', '; rel="next", ; rel="last", ; rel="prev"') .expect(200, done); }) + it('should set Link header field with an Array', function (done) { + var app = express(); + + app.use(function (req, res) { + res.links([ + { + href: 'http://api.example.com/users?page=2', + rel: 'next', + title: 'next chapter', + type: 'text/plain;charset=UTF-8' + }, + { + href: 'http://api.example.com/users?page=5', + rel: 'last', + title: 'the grand finale', + type: 'video/webm' + } + ]); + + res.end(); + }); + + request(app) + .get('/') + .expect('Link', '; rel="next"; title="next chapter"; type="text/plain;charset=UTF-8",' + + ' ; rel="last"; title="the grand finale"; type="video/webm"') + .expect(200, done); + }) }) })