Permalink
Browse files

Added `req.range(size)`

  • Loading branch information...
1 parent e6129d8 commit f4c8a59b17b47d6284b6a3a30f235f99f8d60081 @tj tj committed Jun 18, 2012
Showing with 55 additions and 0 deletions.
  1. +23 −0 lib/request.js
  2. +1 −0 package.json
  3. +31 −0 test/req.range.js
View
@@ -7,6 +7,7 @@ var http = require('http')
, utils = require('./utils')
, connect = require('connect')
, fresh = require('fresh')
+ , parseRange = require('range-parser')
, parse = connect.utils.parseUrl
, mime = connect.mime;
@@ -133,6 +134,28 @@ req.acceptsLanguage = function(lang){
};
/**
+ * Parse Range header field,
+ * capping to the given `size`.
+ *
+ * Unspecified ranges such as "0-" require
+ * knowledge of your resource length. In
+ * the case of a byte range this is of course
+ * the total number of bytes. If the Range
+ * header field is not given `undefined` is returned,
+ * on failure `null` is returned.
+ *
+ * @param {Number} size
+ * @return {Array}
+ * @api public
+ */
+
+req.range = function(size){
+ var range = this.get('Range');
+ if (!range) return;
+ return parseRange(size, range);
+};
+
+/**
* Return an array of Accepted media types
* ordered from highest quality to lowest.
*
View
@@ -12,6 +12,7 @@
"dependencies": {
"connect": "2.3.3",
"commander": "0.6.1",
+ "range-parser": "0.0.3",
"mkdirp": "0.3.3",
"cookie": "0.0.3",
"crc": "0.2.0",
View
@@ -0,0 +1,31 @@
+
+var express = require('../');
+
+function req(ret) {
+ return {
+ get: function(){ return ret }
+ , __proto__: express.request
+ };
+}
+
+describe('req', function(){
+ describe('.range(size)', function(){
+ it('should return parsed ranges', function(){
+ var ret = [{ start: 0, end: 50 }, { start: 60, end: 100 }];
+ ret.type = 'bytes';
+ req('bytes=0-50,60-100').range(120).should.eql(ret);
+ })
+
+ it('should cap to the given size', function(){
+ var ret = [{ start: 0, end: 74 }];
+ ret.type = 'bytes';
+ req('bytes=0-100').range(75).should.eql(ret);
+ })
+
+ it('should have a .type', function(){
+ var ret = [{ start: 0, end: Infinity }];
+ ret.type = 'users';
+ req('users=0-').range(Infinity).should.eql(ret);
+ })
+ })
+})

0 comments on commit f4c8a59

Please sign in to comment.