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

Commit

Permalink
feat: validates query parameters (validateURI)
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-zakharchenko committed Jun 11, 2019
1 parent 00ac00a commit 98ab5eb
Show file tree
Hide file tree
Showing 2 changed files with 324 additions and 52 deletions.
50 changes: 48 additions & 2 deletions lib/units/validateURI.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,60 @@
const deepEqual = require('deep-equal');

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

/**
* Parses a given query string into an Object.
* @param {string} queryString
*/
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
};
}, {});
};

/**
* @param {string} uri
*/
const parseURI = (uri) => {
const parsed = /(\w+)(\?(.+))?/.exec(uri) || [];
const hostname = parsed[1];
const queryString = parsed[3];

return {
hostname,
query: parseQueryString(queryString)
};
};

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);

// Note the different order of arguments between
// "validateURI" and "deepEqual".
const isValid = deepEqual(parsedReal, parsedExpected);
const errors = [];
const isValid = expectedURI === realURI;

if (!isValid) {
errors.push({
message: `Expected "uri" field to equal "${expectedURI}", but got "${realURI}".`
message: `Expected "uri" field to equal "${expectedURI}", but got: "${realURI}".`
});
}

Expand Down
Loading

0 comments on commit 98ab5eb

Please sign in to comment.