|
| 1 | +const deepEqual = require('deep-equal'); |
| 2 | + |
1 | 3 | const APIARY_URI_TYPE = 'text/vnd.apiary.uri';
|
2 | 4 |
|
| 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 | + |
3 | 41 | const validateURI = (expected, real) => {
|
4 | 42 | const { uri: expectedURI } = expected;
|
5 | 43 | 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); |
6 | 53 | const errors = [];
|
7 |
| - const isValid = expectedURI === realURI; |
8 | 54 |
|
9 | 55 | if (!isValid) {
|
10 | 56 | errors.push({
|
11 |
| - message: `Expected "uri" field to equal "${expectedURI}", but got "${realURI}".` |
| 57 | + message: `Expected "uri" field to equal "${expectedURI}", but got: "${realURI}".` |
12 | 58 | });
|
13 | 59 | }
|
14 | 60 |
|
|
0 commit comments