From 9e3b486a7082bfa6c6e0103da38451d79f8ac012 Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Wed, 12 Aug 2020 21:31:11 -0700 Subject: [PATCH] feat: add tags to search query and write data to file in plugin --- gatsby-config.js | 16 ++++++++++++--- plugins/gatsby-source-swiftype/gatsby-node.js | 20 +++++++++---------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/gatsby-config.js b/gatsby-config.js index 0698e173c..d175b98b1 100644 --- a/gatsby-config.js +++ b/gatsby-config.js @@ -1,3 +1,5 @@ +const quote = (str) => `"${str}"`; + module.exports = { siteMetadata: { title: 'New Relic Developers', @@ -48,9 +50,17 @@ module.exports = { file: `${__dirname}/src/data/related-pages.json`, engineKey: 'Ad9HfGjDw4GRkcmJjUut', pageLimit: 5, - getParams: ({ node }) => ({ - path: node.frontmatter.path, - }), + getParams: ({ node }) => { + const { tags, title } = node.frontmatter; + + return { + path: node.frontmatter.path, + q: tags ? tags.map(quote).join(' OR ') : title, + search_fields: { + page: ['tags^10', 'body^5', 'title^1.5', '*'], + }, + }; + }, filterNode: ({ node }) => node.internal.type === 'Mdx' && node.frontmatter.template === 'GuideTemplate', diff --git a/plugins/gatsby-source-swiftype/gatsby-node.js b/plugins/gatsby-source-swiftype/gatsby-node.js index 1f9cfd965..7f6019430 100644 --- a/plugins/gatsby-source-swiftype/gatsby-node.js +++ b/plugins/gatsby-source-swiftype/gatsby-node.js @@ -1,5 +1,7 @@ const fs = require('fs'); +const data = {}; + const appendTrailingSlash = (url) => url.pathname.endsWith('/') ? url : new URL(`${url.pathname}/`, url.origin); @@ -8,16 +10,6 @@ const stripTrailingSlash = (url) => ? new URL(url.replace(/\/$/, ''), url.origin) : url; -exports.onPreBootstrap = ({ reporter }, pluginOptions) => { - const { file } = pluginOptions; - - if (!fs.existsSync(file)) { - reporter.info('gatsby-source-swiftype: Creating data file'); - - fs.writeFileSync(file, '{}'); - } -}; - exports.onCreateNode = async ({ node, getNodesByType }, pluginOptions) => { const { filterNode = () => false, @@ -52,4 +44,12 @@ exports.onCreateNode = async ({ node, getNodesByType }, pluginOptions) => { }, }, }; + + data[pathname] = allParams; +}; + +exports.onPostBootstrap = (_, pluginOptions) => { + const { file } = pluginOptions; + + fs.writeFileSync(file, JSON.stringify(data, null, 2), { flag: 'w' }); };