Skip to content
Myr

Added extname support to `res.format()`. Closes #1024

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by TJ Holowaychuk · committed by TJ Holowaychuk · parent ffcaa04 · Browse files · 2 files+97 added−42 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+97 added−42 removed

  • tests:+59 added−35 removed
  • other:+38 added−7 removed

2 files+97 added−42 removed

modified:lib/response.js+38 added-7 removed
296 unmodified lines
297 * is invoked, otherwise the first match is used. When298 * no match is performed the server responds with299 * 406 "Not Acceptable".300 *301 * Examples:301 * Content-Type is set for you, however if you choose302 * you may alter this within the callback using `res.type()`303 * or `res.set('Content-Type', ...)`.304 *305 * res.format({306 * 'text/plain': function(){305 * res.type('text').send('hey');307 * res.send('hey');308 * },309 * 310 * 'text/html': function(){311 * res.send('<p>hey</p>');
3 unmodified lines
315 * res.send({ message: 'hey' });316 * }317 * });318 *319 * In addition to canonicalized MIME types you may320 * also use extnames mapped to these types:321 *322 * res.format({323 * text: function(){324 * res.send('hey');325 * },326 * 327 * html: function(){328 * res.send('<p>hey</p>');329 * },330 * 331 * json: function(){332 * res.send({ message: 'hey' });333 * }334 * });335 *336 * @param {Object} obj337 * @return {ServerResponse} for chaining338 * @api public339 */340341res.format = function(obj){342 var keys = Object.keys(obj)343 , types = []344 , req = this.req345 , next = req.next346 , accepted = req.accepted347 , type348 , key;349350 // normalize extnames -> mime351 for (var i = 0; i < keys.length; ++i) {352 types.push(~keys[i].indexOf('/')353 ? keys[i]354 : mime.lookup(keys[i]));355 }356357 out:358 for (var i = 0, len = accepted.length; i < len; ++i) {332 for (var j = 0, jlen = keys.length; j < jlen; ++j) {333 if (accept(keys[j].split('/'), accepted[i])) {359 for (var j = 0, jlen = types.length; j < jlen; ++j) {360 if (accept(types[j].split('/'), accepted[i])) {361 key = keys[j];362 type = types[j];363 break out;364 }365 }366 }367340 if (!accepted.length) key = keys.shift();368 if (!accepted.length) {369 key = keys[0];370 type = types[0];371 }372373 if (key) {343 this.set('Content-Type', key);374 this.set('Content-Type', type);375 obj[key](req, this, next);376 } else {377 var err = new Error('Not Acceptable');378 err.status = 406;348 err.types = keys;379 err.types = types;380 next(err);381 }382383 return this;
277 unmodified lines
modified:test/res.format.js+59 added-35 removed