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

Commit 1dfeab4

Browse files
feat: validates query parameters (validateURI)
1 parent 4748564 commit 1dfeab4

File tree

2 files changed

+324
-52
lines changed

2 files changed

+324
-52
lines changed

lib/units/validateURI.js

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,60 @@
1+
const deepEqual = require('deep-equal');
2+
13
const APIARY_URI_TYPE = 'text/vnd.apiary.uri';
24

5+
/**
6+
* Parses a given query string into an Object.
7+
* @param {string} queryString
8+
*/
9+
const parseQueryString = (queryString) => {
10+
if (!queryString) {
11+
return {};
12+
}
13+
14+
return queryString.split('&').reduce((acc, paramString) => {
15+
const [paramName, paramValue] = paramString.split('=');
16+
const nextValue = Object.prototype.hasOwnProperty.call(acc, paramName)
17+
? [].concat(acc[paramName], paramValue)
18+
: paramValue;
19+
20+
return {
21+
...acc,
22+
[paramName]: nextValue
23+
};
24+
}, {});
25+
};
26+
27+
/**
28+
* @param {string} uri
29+
*/
30+
const parseURI = (uri) => {
31+
const parsed = /(\w+)(\?(.+))?/.exec(uri) || [];
32+
const hostname = parsed[1];
33+
const queryString = parsed[3];
34+
35+
return {
36+
hostname,
37+
query: parseQueryString(queryString)
38+
};
39+
};
40+
341
const validateURI = (expected, real) => {
442
const { uri: expectedURI } = expected;
543
const { uri: realURI } = real;
44+
45+
// Parses URI into Objects to deal with
46+
// the order of query parameters.
47+
const parsedExpected = parseURI(expectedURI);
48+
const parsedReal = parseURI(realURI);
49+
50+
// Note the different order of arguments between
51+
// "validateURI" and "deepEqual".
52+
const isValid = deepEqual(parsedReal, parsedExpected);
653
const errors = [];
7-
const isValid = expectedURI === realURI;
854

955
if (!isValid) {
1056
errors.push({
11-
message: `Expected "uri" field to equal "${expectedURI}", but got "${realURI}".`
57+
message: `Expected "uri" field to equal "${expectedURI}", but got: "${realURI}".`
1258
});
1359
}
1460

0 commit comments

Comments
 (0)