Skip to content

Commit

Permalink
feat: add search-params as a dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
troch committed Oct 11, 2016
1 parent 7fa1a8b commit 6ab04d7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 19 deletions.
45 changes: 30 additions & 15 deletions modules/Path.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { getSearch, withoutBrackets, parse, toObject } from 'search-params';

const defaultOrConstrained = (match) =>
'(' + (match ? match.replace(/(^<|>$)/g, '') : '[a-zA-Z0-9-_.~%]+') + ')';

Expand Down Expand Up @@ -54,6 +56,8 @@ const rules = [
}
];

const exists = (val) => val !== undefined && val !== null;

const tokenise = (str, tokens = []) => {
// Look for a matching rule
const matched =
Expand Down Expand Up @@ -86,8 +90,6 @@ const optTrailingSlash = (source, trailingSlash) => {
return source.replace(/\\\/$/, '') + '(?:\\/)?';
};

const withoutBrackets = param => param.replace(/\[\]$/, '');

const appendQueryParam = (params, param, val = '') => {
if (/\[\]$/.test(param)) {
param = withoutBrackets(param);
Expand All @@ -102,18 +104,23 @@ const appendQueryParam = (params, param, val = '') => {
};

const parseQueryParams = path => {
let searchPart = path.split('?')[1];
let searchPart = getSearch(path);
if (!searchPart) return {};

return searchPart
.split('&')
.map(_ => _.split('='))
.reduce((obj, m) => appendQueryParam(obj, m[0], m[1] ? decodeURIComponent(m[1]) : m[1]), {});
return toObject(parse(searchPart));
};

const toSerialisable = val => val !== undefined && val !== null && val !== '' ? `=${val}` : '';
function serialise(key, val) {
if (Array.isArray(val)) {
return val.map(v => serialise(key, v)).join('&');
}

if (val === true) {
return key;
}

const serialise = (key, val) => Array.isArray(val) ? val.map(v => serialise(key, v)).join('&') : key + toSerialisable(val);
return `${key}=${val}`;
}

export default class Path {
static createPath(path) {
Expand Down Expand Up @@ -217,19 +224,27 @@ export default class Path {
const encodedParams = Object.keys(params).reduce(
(acc, key) => {
// Use encodeURI in case of spats
if (params[key] === undefined) {
acc[key] = undefined;
if (!exists(params[key])) {
return acc;
}

const val = params[key];

if (typeof val === 'boolean') {
acc[key] = val;
} else if (Array.isArray(val)) {
acc[key] = val.map(encodeURI);
} else {
acc[key] = Array.isArray(params[key])
? params[key].map(encodeURI)
: encodeURI(params[key]);
acc[key] = encodeURI(val);
}

return acc;
},
{}
);

// Check all params are provided (not search parameters which are optional)
if (this.urlParams.some(p => params[p] === undefined)) throw new Error('Missing parameters');
if (this.urlParams.some(p => !exists(encodedParams[p]))) throw new Error('Missing parameters');

// Check constraints
if (!opts.ignoreConstraints) {
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,8 @@
"rollup-plugin-babel": "^2.3.5",
"should": "^6.0.3",
"yargs": "^3.31.0"
},
"dependencies": {
"search-params": "~1.3.0"
}
}
9 changes: 5 additions & 4 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ describe('Path', function () {
// Successful match & partial match
path.match('/users?offset=31&limit=15').should.eql({ offset: '31', limit: '15' });
path.match('/users?offset=31&offset=30&limit=15').should.eql({ offset: ['31', '30'], limit: '15' });
path.match('/users?offset&limit=15').should.eql({ offset: '', limit: '15' });
path.match('/users?offset&limit=15').should.eql({ offset: true, limit: '15' });
path.match('/users?limit=15').should.eql({ limit: '15' });
path.match('/users?limit=15').should.eql({ limit: '15' });
path.partialMatch('/users?offset&limits=1').should.eql({ offset: '' });
path.partialMatch('/users?offset&limits=1').should.eql({ offset: true });
path.partialMatch('/users?offset=1&offset=2%202&limits=1').should.eql({ offset: ['1', '2 2'] });
path.partialMatch('/users').should.eql({});

Expand All @@ -64,9 +64,10 @@ describe('Path', function () {

path.build({ offset: 31, limit: '15 15' }).should.equal('/users?offset=31&limit=15%2015');
path.build({ offset: 31 }).should.equal('/users?offset=31');
path.build({ offset: 31, limit: '' }).should.equal('/users?offset=31&limit');
path.build({ offset: 31, limit: undefined }).should.equal('/users?offset=31&limit');
path.build({ offset: 31, limit: '' }).should.equal('/users?offset=31&limit=');
path.build({ offset: 31, limit: undefined }).should.equal('/users?offset=31');
path.build({ offset: 31, limit: false }).should.equal('/users?offset=31&limit=false');
path.build({ offset: 31, limit: true }).should.equal('/users?offset=31&limit');
path.build({ offset: [31, 30], limit: false }).should.equal('/users?offset=31&offset=30&limit=false');
path.build({ offset: 31, limit: 15 }, {ignoreSearch: true}).should.equal('/users');
});
Expand Down

0 comments on commit 6ab04d7

Please sign in to comment.