Skip to content

Instantly share code, notes, and snippets.

@ajmalafif
Created January 5, 2021 12:31
Show Gist options
  • Save ajmalafif/07c021359083a22d67d262dc6093db4c to your computer and use it in GitHub Desktop.
Save ajmalafif/07c021359083a22d67d262dc6093db4c to your computer and use it in GitHub Desktop.

Revisions

  1. ajmalafif created this gist Jan 5, 2021.
    69 changes: 69 additions & 0 deletions algolia-queries.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    const escapeStringRegexp = require("escape-string-regexp")

    // const pagePath = `content`
    // const indexName = `Pages`

    const pageQuery = `{
    pages: allMdx {
    edges {
    node {
    id
    frontmatter {
    title
    }
    fields {
    slug
    }
    excerpt(pruneLength: 5000)
    }
    }
    }
    }`
    const postQuery = `{
    posts: allSanityPost {
    edges {
    node {
    id
    title
    slug {
    current
    }
    _rawExcerpt
    }
    }
    }
    }`

    function pageToAlgoliaRecord({ node: { id, frontmatter, fields, ...rest } }) {
    return {
    objectID: id,
    ...frontmatter,
    ...fields,
    ...rest,
    }
    }

    function postToAlgoliaRecord({ node: { id, slug, ...rest } }) {
    return {
    objectID: id,
    ...slug,
    ...rest,
    }
    }

    const queries = [
    {
    query: pageQuery,
    transformer: ({ data }) => data.pages.edges.map(pageToAlgoliaRecord),
    indexName: `Pages`,
    settings: { attributesToSnippet: [`excerpt:20`] },
    },
    {
    query: postQuery,
    transformer: ({ data }) => data.posts.edges.map(postToAlgoliaRecord),
    indexName: `Posts`,
    settings: { attributesToSnippet: [`excerpt:20`] },
    },
    ]

    module.exports = queries