From 27c1481915a6ea2339c0fc717c3bbb29020b81d2 Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Wed, 12 Aug 2020 20:57:40 -0700 Subject: [PATCH] feat: add general params that will be used to fetch from swiftype --- gatsby-config.js | 6 ++++ plugins/gatsby-source-swiftype/gatsby-node.js | 36 ++++++++++++++++--- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/gatsby-config.js b/gatsby-config.js index 0418961d2..541208cdd 100644 --- a/gatsby-config.js +++ b/gatsby-config.js @@ -46,6 +46,12 @@ module.exports = { resolve: 'gatsby-source-swiftype', options: { file: `${__dirname}/src/data/related-pages.json`, + engineKey: 'Ad9HfGjDw4GRkcmJjUut', + pageLimit: 5, + getPath: ({ node }) => node.frontmatter.path, + filterNode: ({ node }) => + node.internal.type === 'Mdx' && + node.frontmatter.template === 'GuideTemplate', }, }, 'gatsby-plugin-sass', diff --git a/plugins/gatsby-source-swiftype/gatsby-node.js b/plugins/gatsby-source-swiftype/gatsby-node.js index 1a3a12af3..9d18bbaa7 100644 --- a/plugins/gatsby-source-swiftype/gatsby-node.js +++ b/plugins/gatsby-source-swiftype/gatsby-node.js @@ -1,5 +1,13 @@ const fs = require('fs'); +const appendTrailingSlash = (url) => + url.pathname.endsWith('/') ? url : new URL(`${url.pathname}/`, url.origin); + +const stripTrailingSlash = (url) => + url.pathname.endsWith('/') + ? new URL(url.replace(/\/$/, ''), url.origin) + : url; + exports.onPreBootstrap = ({ reporter }, pluginOptions) => { const { file } = pluginOptions; @@ -10,10 +18,30 @@ exports.onPreBootstrap = ({ reporter }, pluginOptions) => { } }; -exports.onCreatePage = async ({ page }, pluginOptions) => { - const includePage = pluginOptions.filterPage || (() => false); +exports.onCreateNode = async ({ node, getNodesByType }, pluginOptions) => { + const { + filterNode = () => false, + getPath, + pageLimit, + engineKey, + } = pluginOptions; - if (includePage({ page })) { - console.log(`Fetching ${page.path}`); + if (!filterNode({ node })) { + return; } + + const [{ siteMetadata }] = getNodesByType('Site'); + const { siteUrl } = siteMetadata; + const pathname = getPath({ node }); + const url = new URL(pathname, siteUrl); + + const params = { + engine_key: engineKey, + per_page: pageLimit, + filters: { + page: { + url: [`!${appendTrailingSlash(url)}`, `!${stripTrailingSlash(url)}`], + }, + }, + }; };