Skip to content

Commit

Permalink
refactor: use plain url strings intead of URL instance
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Aug 13, 2020
1 parent a90318d commit 04b1828
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 16 deletions.
6 changes: 4 additions & 2 deletions plugins/gatsby-source-swiftype/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ exports.onCreateNode = async ({ node, getNodesByType }, pluginOptions) => {

const params = getParams({ node });
const pathname = getPath({ node });
const url = new URL(pathname, siteUrl);

const result = await search(url, params, { engineKey, pageLimit });
const result = await search(siteUrl + pathname, params, {
engineKey,
pageLimit,
});

data[pathname] = result;
};
Expand Down
20 changes: 12 additions & 8 deletions plugins/gatsby-source-swiftype/src/search.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
const fetch = require('node-fetch');
const { appendTrailingSlash, stripTrailingSlash } = require('./utils/url');

const normalizeUrl = (urlString) => {
const prefix = urlString.startsWith('!') ? '!' : '';
const url = new URL(urlString.replace(/^!/, ''));
const normalizeUrl = (url) => {
const prefix = url.startsWith('!') ? '!' : '';
const plainUrl = url.replace(/^!/, '');

return [prefix + appendTrailingSlash(url), prefix + stripTrailingSlash(url)];
return [
prefix + appendTrailingSlash(plainUrl),
prefix + stripTrailingSlash(plainUrl),
];
};

const uniq = (arr) => [...new Set(arr)];

module.exports = async (url, params = {}, { engineKey, pageLimit }) => {
const { page: pageFilters = {} } = params.filters || {};

Expand All @@ -26,11 +31,10 @@ module.exports = async (url, params = {}, { engineKey, pageLimit }) => {
...params.filters,
page: {
...pageFilters,
url: [
`!${appendTrailingSlash(url)}`,
`!${stripTrailingSlash(url)}`,
url: uniq([
...normalizeUrl(`!${url}`),
...(pageFilters.url || []).flatMap(normalizeUrl),
],
]),
},
},
}),
Expand Down
26 changes: 20 additions & 6 deletions plugins/gatsby-source-swiftype/src/utils/url.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
exports.appendTrailingSlash = (url) =>
url.pathname.endsWith('/') ? url : new URL(`${url.pathname}/`, url.origin);
const hasQueryParams = (urlString) => {
const url = new URL(urlString);

exports.stripTrailingSlash = (url) =>
url.pathname.endsWith('/')
? new URL(url.replace(/\/$/, ''), url.origin)
: url;
return Boolean(url.search);
};

exports.appendTrailingSlash = (url) => {
if (hasQueryParams(url)) {
return url;
}

return url.endsWith('/') ? url : `${url}/`;
};

exports.stripTrailingSlash = (url) => {
if (hasQueryParams(url)) {
return url;
}

return url.endsWith('/') ? url.replace(/\/$/, '') : url;
};

0 comments on commit 04b1828

Please sign in to comment.