UNPKG

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