request.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const queryUtils = require('query-string');
  2. class FileRequest {
  3. /**
  4. * @param {string} request
  5. */
  6. constructor(request) {
  7. const { file, query } = FileRequest.parse(request);
  8. this.file = file;
  9. this.query = query;
  10. }
  11. /**
  12. * @param {string} request
  13. * @return {{file: string, query: Object}}
  14. */
  15. static parse(request) {
  16. const parts = request.split('?');
  17. const file = parts[0];
  18. const query = parts[1] ? queryUtils.parse(parts[1]) : null;
  19. return { file, query };
  20. }
  21. /**
  22. * @return {string}
  23. */
  24. toString() {
  25. const { file, query } = this;
  26. const queryEncoded = query ? `?${queryUtils.stringify(query)}` : '';
  27. return `${file}${queryEncoded}`;
  28. }
  29. /**
  30. * @return {string}
  31. */
  32. stringify() {
  33. return this.toString();
  34. }
  35. /**
  36. * @return {string}
  37. */
  38. stringifyQuery() {
  39. return queryUtils.stringify(this.query);
  40. }
  41. /**
  42. * @param {FileRequest} request
  43. * @return {boolean}
  44. */
  45. equals(request) {
  46. if (!(request instanceof FileRequest)) {
  47. throw TypeError('request should be instance of FileRequest');
  48. }
  49. return this.toString() === request.toString();
  50. }
  51. /**
  52. * @param {FileRequest} request
  53. * @return {boolean}
  54. */
  55. fileEquals(request) {
  56. return this.file === request.file;
  57. }
  58. /**
  59. * @param {FileRequest} request
  60. * @return {boolean}
  61. */
  62. queryEquals(request) {
  63. return this.stringifyQuery() === request.stringifyQuery();
  64. }
  65. /**
  66. * @param {string} param
  67. * @return {boolean}
  68. */
  69. hasParam(param) {
  70. return this.query && param in this.query;
  71. }
  72. /**
  73. * @param {string} param
  74. * @return {string|null}
  75. */
  76. getParam(param) {
  77. return this.hasParam(param) ? this.query[param] : null;
  78. }
  79. }
  80. module.exports = FileRequest;