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
Provenance
- Commit
cec0c06- Tree
5aa285a- Author
Jonathan Ong <jonathanrichardong@gmail.com>- Committer
Jonathan Ong <jonathanrichardong@gmail.com>- Parent
476f8de
12 files changed+53 added−585 removed
modified:lib/request.js+26 added-120 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6+var accepts = require('accepts');7+var typeis = require('type-is');8 var http = require('http')9 , utils = require('./utils')10 , connect = require('connect')11 , fresh = require('fresh')45 unmodified lines57 }58 };59 60 /**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 lines102 * @return {String}103 * @api public104 */105 102-req.accepts = function(type){103- var args = arguments.length > 1 ? [].slice.apply(arguments) : type;104- return utils.accepts(args, this.get('Accept'));106+req.accepts = function(){107+ var accept = accepts(this);108+ return accept.types.apply(accept, arguments);109 };110 111 /**112 * Check if the given `encoding` is accepted.2 unmodified lines115 * @return {Boolean}116 * @api public117 */118 115-req.acceptsEncoding = function(encoding){116- return !! ~this.acceptedEncodings.indexOf(encoding);119+req.acceptsEncoding = // backwards compatibility120+req.acceptsEncodings = function(){121+ var accept = accepts(this);122+ return accept.encodings.apply(accept, arguments);123 };124 125 /**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 */135 128-req.acceptsCharset = function(charset){129- var accepted = this.acceptedCharsets;130- return accepted.length131- ? !! ~accepted.indexOf(charset)132- : true;136+req.acceptsCharset = // backwards compatibility137+req.acceptsCharsets = function(){138+ var accept = accepts(this);139+ return accept.charsets.apply(accept, arguments);140 };141 142 /**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 */152 144-req.acceptsLanguage = function(lang){145- var accepted = this.acceptedLanguages;146- return accepted.length147- ? !! ~accepted.indexOf(lang)148- : true;153+req.acceptsLanguage = // backwards compatibility154+req.acceptsLanguages = function(lang){155+ var accept = accepts(this);156+ return accept.languages.apply(accept, arguments);157 };158 159 /**160 * Parse Range header field,21 unmodified lines182 return parseRange(size, range);183 };184 185 /**178- * Return an array of encodings.179- *180- * Examples:181- *182- * ['gzip', 'deflate']183- *184- * @return {Array}185- * @api public186- */187-188-req.__defineGetter__('acceptedEncodings', function(){189- var accept = this.get('Accept-Encoding');190- return accept191- ? accept.trim().split(/ *, */)192- : [];193-});194-195-/**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- */213-214-req.__defineGetter__('accepted', function(){215- var accept = this.get('Accept');216- return accept217- ? utils.parseAccept(accept)218- : [];219-});220-221-/**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- */233-234-req.__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-});244-245-/**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- */257-258-req.__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-});268-269-/**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 lines234 * @return {Boolean}235 * @api public236 */237 322-req.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);238+req.is = function(types){239+ if (!Array.isArray(types)) types = [].slice.call(arguments);240+ return typeis(this, types);241 };242 243 /**244 * Return the protocol string "http" or "https"191 unmodified linesmodified:lib/utils.js-121 removed
108 unmodified lines109 110 return ret;111 };112 113-/**114- * Return the acceptable type in `types`, if any.115- *116- * @param {Array} types117- * @param {String} str118- * @return {String}119- * @api private120- */113 122-exports.acceptsArray = function(types, str){123- // accept anything when Accept is not present124- if (!str) return types[0];125-126- // parse127- var accepted = exports.parseAccept(str)128- , normalized = exports.normalizeTypes(types)129- , len = accepted.length;130-131- 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-};139-114 /**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- */149-150-exports.accepts = function(type, str){151- if ('string' == typeof type) type = type.split(/ *, */);152- return exports.acceptsArray(type, str);153-};154-155-/**156- * Check if `type` array is acceptable for `other`.157- *158- * @param {Object} type159- * @param {Object} other160- * @return {Boolean}161- * @api private162- */163-164-exports.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-};170-171-/**172- * Check if accept params are equal.173- *174- * @param {Object} a175- * @param {Object} b176- * @return {Boolean}177- * @api private178- */179-180-function paramsEqual(a, b){181- return !Object.keys(a).some(function(k) {182- return a[k] != b[k];183- });184-}185-186-/**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- */197-198-exports.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-};208-209-/**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- */218-219-exports.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-};234-235-/**115 * Parse accept params `str` returning an116 * object with `.value`, `.quality` and `.params`.117 * also includes `.originalIndex` for stable sorting118 *75 unmodified linesdeleted:test/req.accepted.js-37 removed
12345678910111213141516171819202122232425262728293031323334353637
var express = require('../') , request = require('./support/http');
describe('req', function(){ describe('.accepted', function(){ it('should return an array of accepted media types', function(done){ var app = express();
app.use(function(req, res){ req.accepted[0].value.should.equal('application/json'); req.accepted[1].value.should.equal('text/html'); res.end(); });
request(app) .get('/') .set('Accept', 'text/html;q=.5, application/json') .expect(200, done); })
describe('when Accept is not present', function(){ it('should default to []', function(done){ var app = express();
app.use(function(req, res){ req.accepted.should.have.length(0); res.end(); });
request(app) .get('/') .expect(200, done); }) }) })})deleted:test/req.acceptedCharsets.js-37 removed
12345678910111213141516171819202122232425262728293031323334353637
var express = require('../') , request = require('./support/http');
describe('req', function(){ describe('.acceptedCharsets', function(){ it('should return an array of accepted charsets', function(done){ var app = express();
app.use(function(req, res){ req.acceptedCharsets[0].should.equal('unicode-1-1'); req.acceptedCharsets[1].should.equal('iso-8859-5'); res.end(); });
request(app) .get('/') .set('Accept-Charset', 'iso-8859-5;q=.2, unicode-1-1;q=0.8') .expect(200, done); })
describe('when Accept-Charset is not present', function(){ it('should default to []', function(done){ var app = express();
app.use(function(req, res){ req.acceptedCharsets.should.have.length(0); res.end(); });
request(app) .get('/') .expect(200, done); }) }) })})deleted:test/req.acceptedEncodings.js-37 removed
12345678910111213141516171819202122232425262728293031323334353637
var express = require('../') , request = require('./support/http');
describe('req', function(){ describe('.acceptedEncodings', function(){ it('should return an array of accepted encodings', function(done){ var app = express();
app.use(function(req, res){ req.acceptedEncodings.should.eql(['gzip', 'deflate']); res.end(); });
request(app) .get('/') .set('Accept-Encoding', ' gzip, deflate') .expect(200, done); })
describe('when Accept-Encoding is not present', function(){ it('should default to []', function(done){ var app = express();
app.use(function(req, res){ req.acceptedEncodings.should.have.length(0); res.end(); });
request(app) .get('/') .set('Accept-Encoding', '') .expect(200, done); }) }) })})deleted:test/req.acceptedLanguages.js-37 removed
12345678910111213141516171819202122232425262728293031323334353637
var express = require('../') , request = require('./support/http');
describe('req', function(){ describe('.acceptedLanguages', function(){ it('should return an array of accepted languages', function(done){ var app = express();
app.use(function(req, res){ req.acceptedLanguages[0].should.equal('en-us'); req.acceptedLanguages[1].should.equal('en'); res.end(); });
request(app) .get('/') .set('Accept-Language', 'en;q=.5, en-us') .expect(200, done); })
describe('when Accept-Language is not present', function(){ it('should default to []', function(done){ var app = express();
app.use(function(req, res){ req.acceptedLanguages.should.have.length(0); res.end(); });
request(app) .get('/') .expect(200, done); }) }) })})modified:test/req.accepts.js-13 removed
41 unmodified lines42 .expect('no', done);43 })44 })45 46- it('should accept a comma-delimited list of types', function(done){47- var app = express();48-49- app.use(function(req, res, next){50- res.end(req.accepts('json, html'));51- });52-53- request(app)54- .get('/')55- .set('Accept', 'text/html')56- .expect('html', done);57- })58-46 it('should accept an argument list of type names', function(done){47 var app = express();48 49 app.use(function(req, res, next){75 unmodified linesmodified:test/req.acceptsCharset.js+3 added-3 removed
7 unmodified lines8910111212131415165 unmodified lines222324252626272829304 unmodified lines353637383939404142436 unmodified lines7 unmodified lines it('should return true', function(done){ var app = express();
app.use(function(req, res, next){ res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no'); res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); });
request(app) .get('/')5 unmodified lines it('should return true when present', function(done){ var app = express();
app.use(function(req, res, next){ res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no'); res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); });
request(app) .get('/')4 unmodified lines it('should return false otherwise', function(done){ var app = express();
app.use(function(req, res, next){ res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no'); res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); });
request(app) .get('/')6 unmodified linesmodified:test/req.is.js+12 added-9 removed
2 unmodified lines3 , request = require('./support/http');4 5 function 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 };13 14 return req;15 }1 unmodified line17 describe('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 })23 24 describe('when content-type is not present', function(){25 it('should return false', function(){6 unmodified lines32 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');37 38 req('text/html')39 .is('json')40 .should.be.false;3 unmodified lines44 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');49 50 req('image/jpeg')51 .is('application/json')52 .should.be.false;3 unmodified lines56 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');61 62 req('image/jpeg')63 .is('*/json')64 .should.be.false;2 unmodified lines67 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');72 73 req('text/plain; charset=utf-8')74 .is('*/html')75 .should.be.false;4 unmodified lines80 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');85 86 req('text/html')87 .is('image/*')88 .should.be.false;2 unmodified lines91 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');96 97 req('something/html; charset=utf-8')98 .is('text/*')99 .should.be.false;4 unmodified linesmodified:test/utils.js-171 removed
46 unmodified lines47 utils.escape('<script>foo & "bar"')48 .should.equal('<script>foo & "bar"')49 })50 })51-52-describe('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- })57-58- 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 }]);61-62- utils.parseParams('text/html; q=.2')63- .should.eql([{ value: 'text/html', quality: 0.2, params: {}, originalIndex: 0 }]);64- })65-66- 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 }]);69-70- 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- })75-76- 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- })80-81- 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- })88-89- 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- })94-95- 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- })102-103- 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-})109-110-describe('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- })115-116- it('should provide .subtype', function(){117- var arr = utils.parseAccept('text/html');118- arr[0].subtype.should.equal('html');119- })120-})121-122-describe('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- })129-130- 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- })136-137- 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- })143-144- 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');148-149- utils.accepts(['html', 'application/json'], 'text/plain, application/json')150- .should.equal('application/json');151-152- utils.accepts(['text/html', 'application/json'], 'application/json;q=.5, text/html')153- .should.equal('text/html');154- })155- })156-157- 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');161-162- utils.accepts('html, application/json', 'text/plain, application/json')163- .should.equal('application/json');164-165- utils.accepts('text/html, application/json', 'application/json;q=.5, text/html')166- .should.equal('text/html');167- })168- })169-170- 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- })175-176- it('should return undefined otherwise', function(){177- assert(null == utils.accepts('text/html', 'text/plain, application/json'));178- })179- })180-181- 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- })186-187- it('should return undefined otherwise', function(){188- assert(null == utils.accepts('text/html', 'image/*'));189- })190- })191-192- 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- })197-198- it('should return undefined otherwise', function(){199- assert(null == utils.accepts('text/html', '*/json'));200- })201- })202-203- 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- })208-209- it('should return undefined otherwise', function(){210- assert(null == utils.accepts('html', 'text/plain, application/json'));211- })212-213- it('should support *', function(){214- utils.accepts('html', 'text/*')215- .should.equal('html');216-217- utils.accepts('html', '*/html')218- .should.equal('html');219- })220- })221-})modified:History.md+10 added
1 4.0.0 /2 ==================3 4 * 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`15 16 3.4.7 / 2013-12-1017 ==================18 1249 unmodified linesmodified:package.json+2 added
21 unmodified lines22 }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