handleRangeHeaders.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = handleRangeHeaders;
  6. var _rangeParser = _interopRequireDefault(require("range-parser"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. function handleRangeHeaders(context, content, req, res) {
  9. // assumes express API. For other servers, need to add logic to access
  10. // alternative header APIs
  11. if (res.set) {
  12. res.set("Accept-Ranges", "bytes");
  13. } else {
  14. res.setHeader("Accept-Ranges", "bytes");
  15. }
  16. let range; // Express API
  17. if (req.get) {
  18. range = req.get("range");
  19. } // Node.js API
  20. else {
  21. ({
  22. range
  23. } = req.headers);
  24. }
  25. if (range) {
  26. const ranges = (0, _rangeParser.default)(content.length, range); // unsatisfiable
  27. if (ranges === -1) {
  28. // Express API
  29. if (res.set) {
  30. res.set("Content-Range", `bytes */${content.length}`);
  31. res.status(416);
  32. } // Node.js API
  33. else {
  34. // eslint-disable-next-line no-param-reassign
  35. res.statusCode = 416;
  36. res.setHeader("Content-Range", `bytes */${content.length}`);
  37. }
  38. } else if (ranges === -2) {
  39. // malformed header treated as regular response
  40. context.logger.error("A malformed Range header was provided. A regular response will be sent for this request.");
  41. } else if (ranges.length !== 1) {
  42. // multiple ranges treated as regular response
  43. context.logger.error("A Range header with multiple ranges was provided. Multiple ranges are not supported, so a regular response will be sent for this request.");
  44. } else {
  45. // valid range header
  46. const {
  47. length
  48. } = content; // Express API
  49. if (res.set) {
  50. // Content-Range
  51. res.status(206);
  52. res.set("Content-Range", `bytes ${ranges[0].start}-${ranges[0].end}/${length}`);
  53. } // Node.js API
  54. else {
  55. // Content-Range
  56. // eslint-disable-next-line no-param-reassign
  57. res.statusCode = 206;
  58. res.setHeader("Content-Range", `bytes ${ranges[0].start}-${ranges[0].end}/${length}`);
  59. } // eslint-disable-next-line no-param-reassign
  60. content = content.slice(ranges[0].start, ranges[0].end + 1);
  61. }
  62. }
  63. return content;
  64. }