-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
60 lines (58 loc) · 1.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';
var parse = require('http-range-parse');
var format = require('http-content-range-format');
module.exports = function middleware(options) {
options = options || {};
var accept = options.accept || ['items'];
if(typeof accept == 'string') {
accept = [accept];
}
var limit = options.limit || 10;
var lengthFn = typeof options.length == 'number'
? function(cb) { cb(null, options.length); }
: typeof options.length == 'undefined'
? function(cb) { cb(); }
: options.length;
return function contentRange(req, res, next) {
var parsed = req.headers.range
? parse(req.headers.range)
: accept.length == 1
? {
unit: accept[0],
first: 0,
last: limit - 1
}
: null;
req.range = parsed;
res.setHeader('Accept-Ranges', accept.join(', '));
if(req.headers.range) {
res.status(206);
}
lengthFn(function(err, length) {
if(err) {
return next(err);
}
if(accept.length == 1 && typeof parsed.first == 'number'
&& typeof parsed.last == 'number') {
res.setHeader('Content-Range', format({
first: parsed.first,
last: parsed.last,
unit: accept[0],
length: length
}));
}
res.range = function(opts) {
if(!opts.unit && !parsed && accept.length > 1) {
throw new Error('Content-Range unit is ambigous');
}
res.setHeader('Content-Range', format({
unit: opts.unit || parsed.unit || accept[0],
first: opts.hasOwnProperty('first') ? opts.first : parsed.first,
last: opts.hasOwnProperty('last') ? opts.last : parsed.last,
length: opts.hasOwnProperty('length') ? opts.length : parsed.length,
}));
};
next();
});
};
};