Skip to content
Myr

refactor req.is and req.accepts*

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

authored by Jonathan Ong · committed by Jonathan Ong · parent 476f8de · Browse files · 12 files+53 added−585 removed
This commit

State

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

Diff stats

12 files+53 added−585 removed

  • tests:+15 added−344 removed
  • other:+38 added−241 removed

12 files+53 added−585 removed

modified:lib/request.js+26 added-120 removed
1 unmodified line
2/**3 * Module dependencies.4 */56var accepts = require('accepts');7var typeis = require('type-is');8var http = require('http')9 , utils = require('./utils')10 , connect = require('connect')11 , fresh = require('fresh')
45 unmodified lines
57 }58};5960/**61 * To do: update docs.62 *63 * Check if the given `type(s)` is acceptable, returning64 * the best match when true, otherwise `undefined`, in which65 * case you should respond with 406 "Not Acceptable".66 *
35 unmodified lines
102 * @return {String}103 * @api public104 */105102req.accepts = function(type){103 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;104 return utils.accepts(args, this.get('Accept'));106req.accepts = function(){107 var accept = accepts(this);108 return accept.types.apply(accept, arguments);109};110111/**112 * Check if the given `encoding` is accepted.
2 unmodified lines
115 * @return {Boolean}116 * @api public117 */118115req.acceptsEncoding = function(encoding){116 return !! ~this.acceptedEncodings.indexOf(encoding);119req.acceptsEncoding = // backwards compatibility120req.acceptsEncodings = function(){121 var accept = accepts(this);122 return accept.encodings.apply(accept, arguments);123};124125/**126 * To do: update docs.127 *128 * Check if the given `charset` is acceptable,129 * otherwise you should respond with 406 "Not Acceptable".130 *131 * @param {String} charset132 * @return {Boolean}133 * @api public134 */135128req.acceptsCharset = function(charset){129 var accepted = this.acceptedCharsets;130 return accepted.length131 ? !! ~accepted.indexOf(charset)132 : true;136req.acceptsCharset = // backwards compatibility137req.acceptsCharsets = function(){138 var accept = accepts(this);139 return accept.charsets.apply(accept, arguments);140};141142/**143 * To do: update docs.144 *145 * Check if the given `lang` is acceptable,146 * otherwise you should respond with 406 "Not Acceptable".147 *148 * @param {String} lang149 * @return {Boolean}150 * @api public151 */152144req.acceptsLanguage = function(lang){145 var accepted = this.acceptedLanguages;146 return accepted.length147 ? !! ~accepted.indexOf(lang)148 : true;153req.acceptsLanguage = // backwards compatibility154req.acceptsLanguages = function(lang){155 var accept = accepts(this);156 return accept.languages.apply(accept, arguments);157};158159/**160 * Parse Range header field,
21 unmodified lines
182 return parseRange(size, range);183};184185/**178 * Return an array of encodings.179 *180 * Examples:181 *182 * ['gzip', 'deflate']183 *184 * @return {Array}185 * @api public186 */187188req.__defineGetter__('acceptedEncodings', function(){189 var accept = this.get('Accept-Encoding');190 return accept191 ? accept.trim().split(/ *, */)192 : [];193});194195/**196 * Return an array of Accepted media types197 * ordered from highest quality to lowest.198 *199 * Examples:200 *201 * [ { value: 'application/json',202 * quality: 1,203 * type: 'application',204 * subtype: 'json' },205 * { value: 'text/html',206 * quality: 0.5,207 * type: 'text',208 * subtype: 'html' } ]209 *210 * @return {Array}211 * @api public212 */213214req.__defineGetter__('accepted', function(){215 var accept = this.get('Accept');216 return accept217 ? utils.parseAccept(accept)218 : [];219});220221/**222 * Return an array of Accepted languages223 * ordered from highest quality to lowest.224 *225 * Examples:226 *227 * Accept-Language: en;q=.5, en-us228 * ['en-us', 'en']229 *230 * @return {Array}231 * @api public232 */233234req.__defineGetter__('acceptedLanguages', function(){235 var accept = this.get('Accept-Language');236 return accept237 ? utils238 .parseParams(accept)239 .map(function(obj){240 return obj.value;241 })242 : [];243});244245/**246 * Return an array of Accepted charsets247 * ordered from highest quality to lowest.248 *249 * Examples:250 *251 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8252 * ['unicode-1-1', 'iso-8859-5']253 *254 * @return {Array}255 * @api public256 */257258req.__defineGetter__('acceptedCharsets', function(){259 var accept = this.get('Accept-Charset');260 return accept261 ? utils262 .parseParams(accept)263 .map(function(obj){264 return obj.value;265 })266 : [];267});268269/**186 * Return the value of param `name` when present or `defaultValue`.187 *188 * - Checks route placeholders, ex: _/user/:id_189 * - Checks body params, ex: id=12, {"id":12}
44 unmodified lines
234 * @return {Boolean}235 * @api public236 */237322req.is = function(type){323 var ct = this.get('Content-Type');324 if (!ct) return false;325 ct = ct.split(';')[0];326 if (!~type.indexOf('/')) type = mime.lookup(type);327 if (~type.indexOf('*')) {328 type = type.split('/');329 ct = ct.split('/');330 if ('*' == type[0] && type[1] == ct[1]) return true;331 if ('*' == type[1] && type[0] == ct[0]) return true;332 return false;333 }334 return !! ~ct.indexOf(type);238req.is = function(types){239 if (!Array.isArray(types)) types = [].slice.call(arguments);240 return typeis(this, types);241};242243/**244 * Return the protocol string "http" or "https"
191 unmodified lines
modified:lib/utils.js-121 removed
108 unmodified lines
109110 return ret;111};112113/**114 * Return the acceptable type in `types`, if any.115 *116 * @param {Array} types117 * @param {String} str118 * @return {String}119 * @api private120 */113122exports.acceptsArray = function(types, str){123 // accept anything when Accept is not present124 if (!str) return types[0];125126 // parse127 var accepted = exports.parseAccept(str)128 , normalized = exports.normalizeTypes(types)129 , len = accepted.length;130131 for (var i = 0; i < len; ++i) {132 for (var j = 0, jlen = types.length; j < jlen; ++j) {133 if (exports.accept(normalized[j], accepted[i])) {134 return types[j];135 }136 }137 }138};139114/**141 * Check if `type(s)` are acceptable based on142 * the given `str`.143 *144 * @param {String|Array} type(s)145 * @param {String} str146 * @return {Boolean|String}147 * @api private148 */149150exports.accepts = function(type, str){151 if ('string' == typeof type) type = type.split(/ *, */);152 return exports.acceptsArray(type, str);153};154155/**156 * Check if `type` array is acceptable for `other`.157 *158 * @param {Object} type159 * @param {Object} other160 * @return {Boolean}161 * @api private162 */163164exports.accept = function(type, other){165 var t = type.value.split('/');166 return (t[0] == other.type || '*' == other.type)167 && (t[1] == other.subtype || '*' == other.subtype)168 && paramsEqual(type.params, other.params);169};170171/**172 * Check if accept params are equal.173 *174 * @param {Object} a175 * @param {Object} b176 * @return {Boolean}177 * @api private178 */179180function paramsEqual(a, b){181 return !Object.keys(a).some(function(k) {182 return a[k] != b[k];183 });184}185186/**187 * Parse accept `str`, returning188 * an array objects containing189 * `.type` and `.subtype` along190 * with the values provided by191 * `parseQuality()`.192 *193 * @param {Type} name194 * @return {Type}195 * @api private196 */197198exports.parseAccept = function(str){199 return exports200 .parseParams(str)201 .map(function(obj){202 var parts = obj.value.split('/');203 obj.type = parts[0];204 obj.subtype = parts[1];205 return obj;206 });207};208209/**210 * Parse quality `str`, returning an211 * array of objects with `.value`,212 * `.quality` and optional `.params`213 *214 * @param {String} str215 * @return {Array}216 * @api private217 */218219exports.parseParams = function(str){220 return str221 .split(/ *, */)222 .map(acceptParams)223 .filter(function(obj){224 return obj.quality;225 })226 .sort(function(a, b){227 if (a.quality === b.quality) {228 return a.originalIndex - b.originalIndex;229 } else {230 return b.quality - a.quality;231 }232 });233};234235/**115 * Parse accept params `str` returning an116 * object with `.value`, `.quality` and `.params`.117 * also includes `.originalIndex` for stable sorting118 *
75 unmodified lines
deleted:test/req.accepted.js-37 removed
deleted:test/req.acceptedCharsets.js-37 removed
deleted:test/req.acceptedEncodings.js-37 removed
deleted:test/req.acceptedLanguages.js-37 removed
modified:test/req.accepts.js-13 removed
41 unmodified lines
42 .expect('no', done);43 })44 })4546 it('should accept a comma-delimited list of types', function(done){47 var app = express();4849 app.use(function(req, res, next){50 res.end(req.accepts('json, html'));51 });5253 request(app)54 .get('/')55 .set('Accept', 'text/html')56 .expect('html', done);57 })5846 it('should accept an argument list of type names', function(done){47 var app = express();4849 app.use(function(req, res, next){
75 unmodified lines
modified:test/req.acceptsCharset.js+3 added-3 removed
modified:test/req.is.js+12 added-9 removed
2 unmodified lines
3 , request = require('./support/http');45function req(ct) {6 var req = {7 headers: { 'content-type': ct }8 , __proto__: express.request7 headers: {8 'content-type': ct,9 'transfer-encoding': 'chunked'10 },11 __proto__: express.request12 };1314 return req;15}
1 unmodified line
17describe('req.is()', function(){18 it('should ignore charset', function(){19 req('application/json; charset=utf-8')20 .is('json')18 .should.be.true;21 .should.equal('json');22 })2324 describe('when content-type is not present', function(){25 it('should return false', function(){
6 unmodified lines
32 describe('when given an extension', function(){33 it('should lookup the mime type', function(){34 req('application/json')35 .is('json')33 .should.be.true;36 .should.equal('json');3738 req('text/html')39 .is('json')40 .should.be.false;
3 unmodified lines
44 describe('when given a mime type', function(){45 it('should match', function(){46 req('application/json')47 .is('application/json')45 .should.be.true;48 .should.equal('application/json');4950 req('image/jpeg')51 .is('application/json')52 .should.be.false;
3 unmodified lines
56 describe('when given */subtype', function(){57 it('should match', function(){58 req('application/json')59 .is('*/json')57 .should.be.true;60 .should.equal('application/json');6162 req('image/jpeg')63 .is('*/json')64 .should.be.false;
2 unmodified lines
67 describe('with a charset', function(){68 it('should match', function(){69 req('text/html; charset=utf-8')70 .is('*/html')68 .should.be.true;71 .should.equal('text/html');7273 req('text/plain; charset=utf-8')74 .is('*/html')75 .should.be.false;
4 unmodified lines
80 describe('when given type/*', function(){81 it('should match', function(){82 req('image/png')83 .is('image/*')81 .should.be.true;84 .should.equal('image/png');8586 req('text/html')87 .is('image/*')88 .should.be.false;
2 unmodified lines
91 describe('with a charset', function(){92 it('should match', function(){93 req('text/html; charset=utf-8')94 .is('text/*')92 .should.be.true;95 .should.equal('text/html');9697 req('something/html; charset=utf-8')98 .is('text/*')99 .should.be.false;
4 unmodified lines
modified:test/utils.js-171 removed
46 unmodified lines
47 utils.escape('<script>foo & "bar"')48 .should.equal('&lt;script&gt;foo &amp; &quot;bar&quot;')49 })50})5152describe('utils.parseParams(str)', function(){53 it('should default quality to 1', function(){54 utils.parseParams('text/html')55 .should.eql([{ value: 'text/html', quality: 1, params: {}, originalIndex: 0 }]);56 })5758 it('should parse qvalues', function(){59 utils.parseParams('text/html; q=0.5')60 .should.eql([{ value: 'text/html', quality: 0.5, params: {}, originalIndex: 0 }]);6162 utils.parseParams('text/html; q=.2')63 .should.eql([{ value: 'text/html', quality: 0.2, params: {}, originalIndex: 0 }]);64 })6566 it('should parse accept parameters', function(){67 utils.parseParams('application/json; ver=2.0')68 .should.eql([{ value: 'application/json', quality: 1, params: {ver: "2.0"}, originalIndex: 0 }]);6970 utils.parseParams('text/html; q=0.5; level=2')71 .should.eql([{ value: 'text/html', quality: 0.5, params: {level: "2"}, originalIndex: 0 }]);72 utils.parseParams('text/html;q=.2;ver=beta')73 .should.eql([{ value: 'text/html', quality: 0.2, params: {ver: "beta"}, originalIndex: 0 }]);74 })7576 it('should work with messed up whitespace', function(){77 utils.parseParams('text/html ; q = .2')78 .should.eql([{ value: 'text/html', quality: 0.2, params: {}, originalIndex: 0 }]);79 })8081 it('should work with multiples', function(){82 var str = 'da, en;q=.5, en-gb;q=.8';83 var arr = utils.parseParams(str);84 arr[0].value.should.equal('da');85 arr[1].value.should.equal('en-gb');86 arr[2].value.should.equal('en');87 })8889 it('should work with long lists', function(){90 var str = 'en, nl, fr, de, ja, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl';91 var arr = utils.parseParams(str).map(function(o){ return o.value });92 arr.should.eql(str.split(', '));93 })9495 it('should sort by quality', function(){96 var str = 'text/plain;q=.2, application/json, text/html;q=0.5';97 var arr = utils.parseParams(str);98 arr[0].value.should.equal('application/json');99 arr[1].value.should.equal('text/html');100 arr[2].value.should.equal('text/plain');101 })102103 it('should exclude those with a quality of 0', function(){104 var str = 'text/plain;q=.2, application/json, text/html;q=0';105 var arr = utils.parseParams(str);106 arr.should.have.length(2);107 })108})109110describe('utils.parseAccept(str)', function(){111 it('should provide .type', function(){112 var arr = utils.parseAccept('text/html');113 arr[0].type.should.equal('text');114 })115116 it('should provide .subtype', function(){117 var arr = utils.parseAccept('text/html');118 arr[0].subtype.should.equal('html');119 })120})121122describe('utils.accepts(type, str)', function(){123 describe('when a string is not given', function(){124 it('should return the value', function(){125 utils.accepts('text/html')126 .should.equal('text/html');127 })128 })129130 describe('when a string is empty', function(){131 it('should return the value', function(){132 utils.accepts('text/html', '')133 .should.equal('text/html');134 })135 })136137 describe('when */* is given', function(){138 it('should return the value', function(){139 utils.accepts('text/html', 'text/plain, */*')140 .should.equal('text/html');141 })142 })143144 describe('when an array is given', function(){145 it('should return the best match', function(){146 utils.accepts(['html', 'json'], 'text/plain, application/json')147 .should.equal('json');148149 utils.accepts(['html', 'application/json'], 'text/plain, application/json')150 .should.equal('application/json');151152 utils.accepts(['text/html', 'application/json'], 'application/json;q=.5, text/html')153 .should.equal('text/html');154 })155 })156157 describe('when a comma-delimited list is give', function(){158 it('should behave like an array', function(){159 utils.accepts('html, json', 'text/plain, application/json')160 .should.equal('json');161162 utils.accepts('html, application/json', 'text/plain, application/json')163 .should.equal('application/json');164165 utils.accepts('text/html, application/json', 'application/json;q=.5, text/html')166 .should.equal('text/html');167 })168 })169170 describe('when accepting type/subtype', function(){171 it('should return the value when present', function(){172 utils.accepts('text/html', 'text/plain, text/html')173 .should.equal('text/html');174 })175176 it('should return undefined otherwise', function(){177 assert(null == utils.accepts('text/html', 'text/plain, application/json'));178 })179 })180181 describe('when accepting */subtype', function(){182 it('should return the value when present', function(){183 utils.accepts('text/html', 'text/*')184 .should.equal('text/html');185 })186187 it('should return undefined otherwise', function(){188 assert(null == utils.accepts('text/html', 'image/*'));189 })190 })191192 describe('when accepting type/*', function(){193 it('should return the value when present', function(){194 utils.accepts('text/html', '*/html')195 .should.equal('text/html');196 })197198 it('should return undefined otherwise', function(){199 assert(null == utils.accepts('text/html', '*/json'));200 })201 })202203 describe('when an extension is given', function(){204 it('should return the value when present', function(){205 utils.accepts('html', 'text/html, application/json')206 .should.equal('html');207 })208209 it('should return undefined otherwise', function(){210 assert(null == utils.accepts('html', 'text/plain, application/json'));211 })212213 it('should support *', function(){214 utils.accepts('html', 'text/*')215 .should.equal('html');216217 utils.accepts('html', '*/html')218 .should.equal('html');219 })220 })221})
modified:History.md+10 added
14.0.0 /2==================34 * remove binary (moved to [express-generator](https://github.com/expressjs/generator))5 * refactor6 - `req.accepts*` with [accepts](https://github.com/expressjs/accepts)7 - `req.is` with [type-is](https://github.com/expressjs/type-is)8 * change9 - `req.accepts[x]` -> `req.accepts[x]s`10 * remove11 - `req.acceptedEncodings`12 - `req.accepted`13 - `req.acceptedLanguages`14 - `req.acceptedCharsets`15163.4.7 / 2013-12-1017==================18
1249 unmodified lines
modified:package.json+2 added
21 unmodified lines
22 }23 ],24 "dependencies": {25 "connect": "2.12.0",26 "accepts": "1.0.0",27 "type-is": "1.0.0",28 "range-parser": "0.0.4",29 "cookie": "0.1.0",30 "buffer-crc32": "0.2.1",31 "fresh": "0.2.0",
38 unmodified lines