How can I add an Algolia index to Gatsby GraphQL?

Viewed 37

I would like to obtain all (or a subset) of my records from an Algolia index and access them via GraphQL. I know there is a Gatsby plugin that allows you to do the opposite i.e., add data from a GraphQL query to Algolia, but not the other way around. I have been able to get the tutorial for adding GraphQL data to work, but I have not had any success when trying to go beyond hardcoded arrays (this is in the gatsby-node.js file):

const algoliasearch = require("algoliasearch/lite");

const searchClient = algoliasearch(
    process.env.GATSBY_ALGOLIA_APP_ID,
    process.env.GATSBY_ALGOLIA_SEARCH_KEY
)

const searchIndex = searchClient.initIndex(process.env.GATSBY_ALGOLIA_INDEX_NAME)

exports.sourceNodes = ({ actions, createNodeId, createContentDigest }) => {    
    searchIndex.search("", {
        attributesToRetrieve: ["name", "url"]
    }).then(({ hits }) => {
        hits.forEach(hit => {
            const node = {
                name: hit.name,
                url: hit.url,
                id: createNodeId(`hit-${hit.name}`),
                internal: {
                    type: "hit",
                    contentDigest: createContentDigest(hit),
                },
            }
            actions.createNode(hit)
        })
    });
}

While the console successfully logs the array of nodes, and the verbose Gatsby deploy output includes the "hit" node as a node type, they do not appear in the GraphQL explorer.

Any help is greatly appreciated, thank you!

0 Answers
Related