You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.5 KiB

7 years ago
  1. var util = require('util');
  2. /**
  3. * Module exports.
  4. */
  5. exports.parse = parse;
  6. exports.format = format;
  7. /**
  8. * Parse extensions header value
  9. */
  10. function parse(value) {
  11. value = value || '';
  12. var extensions = {};
  13. value.split(',').forEach(function(v) {
  14. var params = v.split(';');
  15. var token = params.shift().trim();
  16. var paramsList = extensions[token] = extensions[token] || [];
  17. var parsedParams = {};
  18. params.forEach(function(param) {
  19. var parts = param.trim().split('=');
  20. var key = parts[0];
  21. var value = parts[1];
  22. if (typeof value === 'undefined') {
  23. value = true;
  24. } else {
  25. // unquote value
  26. if (value[0] === '"') {
  27. value = value.slice(1);
  28. }
  29. if (value[value.length - 1] === '"') {
  30. value = value.slice(0, value.length - 1);
  31. }
  32. }
  33. (parsedParams[key] = parsedParams[key] || []).push(value);
  34. });
  35. paramsList.push(parsedParams);
  36. });
  37. return extensions;
  38. }
  39. /**
  40. * Format extensions header value
  41. */
  42. function format(value) {
  43. return Object.keys(value).map(function(token) {
  44. var paramsList = value[token];
  45. if (!util.isArray(paramsList)) {
  46. paramsList = [paramsList];
  47. }
  48. return paramsList.map(function(params) {
  49. return [token].concat(Object.keys(params).map(function(k) {
  50. var p = params[k];
  51. if (!util.isArray(p)) p = [p];
  52. return p.map(function(v) {
  53. return v === true ? k : k + '=' + v;
  54. }).join('; ');
  55. })).join('; ');
  56. }).join(', ');
  57. }).join(', ');
  58. }