Search code examples
node.jsgatsbyghost-bloglunrjs

Gatsby Lunr Plugin with Ghost source


Trying to implement search functionality in Gatsby with the gastby-plugin-lunr plugin.

My gatsby-config.js:

{
  resolve: `gatsby-plugin-lunr`,
  options: {
    languages: [
      {
        name: 'en'
      }
    ],
    fields: [
      { name: 'title', store: true, attributes: { boost: 20 }}
    ],
    resolvers: {
      allGhostPost: {
        title: node => node.title
      }
    }
  }
}

But my index remains empty. Already tried to change the title node to node.fields.title - still didn't work.

My search component:

const ContactPage: FunctionComponent = () => {
  const [results, setResults] = useState([]);
  const [query, setQuery] = useState('');

  const search = (event) => {
    const query = event.target.value;
    if (!query || !(window as any).__LUNR__) {
      setResults([]);
    }
    const lunrIndex =  (window as any).__LUNR__['en'];
    const res = lunrIndex.index.search(query);
    setResults(res);
    setQuery(query);
  };

  return (
    <Layout header={<DefaultHeader/>}>
      <input type="text" value={query} onChange={search} />
      <ul>{results.map(page => <li>{page}</li>)}</ul>
    </Layout>
  )
};

Anyone got an idea?


Solution

  • Fixed it by changing the resolvers to:

       resolvers: {
          GhostPost: {
            title: node => node.title
          }
        }