Resolving Linked Content in Gatsby GraphQL

Follow

While you are sourcing and querying content in gatsby, you are likely to come across a scenario where you need to retrieve a content item and its related content. In Agility CMS, Linked Content fields are used to related content to one another in various ways.

When querying a Post, for example, you may want to also retrieve the details for the Author. On your Post GraphQL node, you may notice an author property, however, it will only contain a contentid reference, not the entire node representing the Author.

You'll need to resolve this Linked Content when you need it.

How to Resolve Linked Content

In the agility-gatsby-starter, we resolve Linked Content by using Gatsby Resolvers

Resolvers are added to your gatsby-node.js in your site, and they allow you to add a new field to your content node which will handle resolving your Linked Content reference.

This means you are telling GraphQL, when you query a specific property on a node, it will actually run a function to go and get your Linked Content and return it.

An example of this can be found here in our starter site:

//gatsy-node.js
const agility = require('./src/agility/utils')
...
//CREATE RESOLVERS *******************************************************************************************
exports.createResolvers = (args) => {

	const { createResolvers, getNode, createNodeId, createNode, createContentDigest, configOptions } = args;

	const resolvers = {
        //on the 'agilityPost' node type...
        agilityPost: {
            //get the sitemap node that represents this item - useful for retrieving the URL for the item
            sitemapNode: agility.getDynamicPageItemSitemapNode(),
            

            //if we had a linked content field for 'author', this is how we'd get the author for this post in a single GraphQl query
            linkedContent_agilityAuthor: agility.getLinkedContentItem({ type: 'agilityAuthor', linkedContentFieldName: 'author' })
        },

        
        //if we had an 'Image Slider' module and it had a list of slides via a linked content field called 'slides', this is how we'd retrieve a list of those slides in a single GraphQL query
        agilityImageSlider: {
           linkedContent_agilitySlides: agility.getLinkedContentList({ type: 'agilitySlide', linkedContentFieldName: 'slides' })
         }
    }
	createResolvers(resolvers)
}
0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.