algolia / gatsby-plugin-algolia

A plugin to push to Algolia based on graphQl queries
https://yarn.pm/gatsby-plugin-algolia
Apache License 2.0
179 stars 45 forks source link

Support pathPrefix/prefixPaths #36

Open saschwarz opened 5 years ago

saschwarz commented 5 years ago

Currently, the user has to append the Gatsby pathPrefix https://www.gatsbyjs.org/docs/path-prefix/ manually in their transformer in order for Algolia to have the correct URL (assuming the slug is rendered directly in the search results).

It would be helpful if there were at least a discussion of the best practices for search when the site is hosted at a pathPrefix.

This is what I ended up doing:

url = require('url')

const postQuery = `{
  posts: allMarkdownRemark(
    edges {
      node {
        objectID: id
        fields {
          slug
        }
        frontmatter {
          title
          date(formatString: "MMM D, YYYY")
          description
          tags
        }
        excerpt(pruneLength: 1000)
      }
    }
  }
  site {
    pathPrefix
    siteMetadata {
      siteUrl
    }
  }
}`

const flatten = (arr, baseUrl) =>
  arr.map(({ node: { frontmatter, fields, ...rest } }) => ({
    ...fields,
    ...frontmatter,
    ...rest,
    slug: url.resolve(baseUrl, fields.slug)
  }))
const settings = { attributesToSnippet: [`excerpt:20`] }

const queries = [
  {
    query: postQuery,
    transformer: ({ data }) => flatten(data.posts.edges,
      url.resolve(data.site.siteMetadata.siteUrl, data.site.pathPrefix)),
    indexName: `Posts`,
    settings,
  },
]

module.exports = queries
Haroenv commented 5 years ago

It seems like this works quite well with the transformer, do you have a suggested way to solve this differently? I don't think the query will resolve the query with full URL via graphql without additional processing, which is more flexible with transformers.

What's your idea to fix this?

saschwarz commented 5 years ago

I'm sorry I wasn't clear. Using transformers is a flexible approach.

As someone new to this plugin/Algolia this was a problem I encountered. So I thought it would be helpful to other new users to add a note (and example?) in the documentation to either use Gatsby's Link component when rendering results or to manually prepend it in the transformer.