Skip to content
This repository was archived by the owner on Nov 8, 2024. It is now read-only.

Commit 5bd3333

Browse files
fix: uses native "url" module for URI parsing
1 parent c830ff6 commit 5bd3333

File tree

1 file changed

+15
-33
lines changed

1 file changed

+15
-33
lines changed

lib/units/validateURI.js

+15-33
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,34 @@
1+
const url = require('url');
12
const deepEqual = require('deep-equal');
23

34
const APIARY_URI_TYPE = 'text/vnd.apiary.uri';
45

56
/**
6-
* Parses a given query string into an Object.
7-
* @param {string} queryString
8-
* @returns {Object<string, string | string[]>}
9-
*/
10-
const parseQueryString = (queryString) => {
11-
if (!queryString) {
12-
return {};
13-
}
14-
15-
return queryString.split('&').reduce((acc, paramString) => {
16-
const [paramName, paramValue] = paramString.split('=');
17-
const nextValue = Object.prototype.hasOwnProperty.call(acc, paramName)
18-
? [].concat(acc[paramName], paramValue)
19-
: paramValue;
20-
21-
return {
22-
...acc,
23-
[paramName]: nextValue
24-
};
25-
}, {});
26-
};
27-
28-
/**
7+
* Parses the given URI and returns the properties
8+
* elligible for comparison. Leaves out raw properties like "path"
9+
* that cannot be compared due to struct query parameters order.
2910
* @param {string} uri
11+
* @returns {Object<string, string | number>}
3012
*/
3113
const parseURI = (uri) => {
32-
const parsed = /(\w+)(\?(.+))?/.exec(uri) || [];
33-
const hostname = parsed[1];
34-
const queryString = parsed[3];
35-
14+
const { pathname, port, hash, query } = url.parse(uri, true);
3615
return {
37-
hostname,
38-
query: parseQueryString(queryString)
16+
pathname,
17+
port,
18+
hash,
19+
query
3920
};
4021
};
4122

4223
const validateURI = (expected, real) => {
4324
const { uri: expectedURI } = expected;
4425
const { uri: realURI } = real;
4526

46-
// Parses URI into Objects to deal with
47-
// the order of query parameters.
48-
const parsedExpected = parseURI(expectedURI);
49-
const parsedReal = parseURI(realURI);
27+
// Parses URI to perform a correct comparison:
28+
// - literal comparison of pathname
29+
// - order-insensitive comparison of query parameters
30+
const parsedExpected = parseURI(expectedURI, true);
31+
const parsedReal = parseURI(realURI, true);
5032

5133
// Note the different order of arguments between
5234
// "validateURI" and "deepEqual".

0 commit comments

Comments
 (0)