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

Commit

Permalink
fix: uses native "url" module for URI parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-zakharchenko committed Jun 18, 2019
1 parent c830ff6 commit 5bd3333
Showing 1 changed file with 15 additions and 33 deletions.
48 changes: 15 additions & 33 deletions lib/units/validateURI.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,34 @@
const url = require('url');
const deepEqual = require('deep-equal');

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

/**
* Parses a given query string into an Object.
* @param {string} queryString
* @returns {Object<string, string | string[]>}
*/
const parseQueryString = (queryString) => {
if (!queryString) {
return {};
}

return queryString.split('&').reduce((acc, paramString) => {
const [paramName, paramValue] = paramString.split('=');
const nextValue = Object.prototype.hasOwnProperty.call(acc, paramName)
? [].concat(acc[paramName], paramValue)
: paramValue;

return {
...acc,
[paramName]: nextValue
};
}, {});
};

/**
* Parses the given URI and returns the properties
* elligible for comparison. Leaves out raw properties like "path"
* that cannot be compared due to struct query parameters order.
* @param {string} uri
* @returns {Object<string, string | number>}
*/
const parseURI = (uri) => {
const parsed = /(\w+)(\?(.+))?/.exec(uri) || [];
const hostname = parsed[1];
const queryString = parsed[3];

const { pathname, port, hash, query } = url.parse(uri, true);
return {
hostname,
query: parseQueryString(queryString)
pathname,
port,
hash,
query
};
};

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

// Parses URI into Objects to deal with
// the order of query parameters.
const parsedExpected = parseURI(expectedURI);
const parsedReal = parseURI(realURI);
// Parses URI to perform a correct comparison:
// - literal comparison of pathname
// - order-insensitive comparison of query parameters
const parsedExpected = parseURI(expectedURI, true);
const parsedReal = parseURI(realURI, true);

// Note the different order of arguments between
// "validateURI" and "deepEqual".
Expand Down

0 comments on commit 5bd3333

Please sign in to comment.