Skip to content

Instantly share code, notes, and snippets.

@coreyward
Created September 15, 2020 18:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreyward/602152c09fc53204e1c8a1281d7b6630 to your computer and use it in GitHub Desktop.
Save coreyward/602152c09fc53204e1c8a1281d7b6630 to your computer and use it in GitHub Desktop.
Extending Gatsby GraphQL schema with interfaces to query shared fields across multiple similar types
const path = require("path")
const fs = require("fs")
// Extend GraphQL Types
exports.sourceNodes = ({ actions }) => {
const { createTypes } = actions
const typeDefs = fs.readFileSync(
path.resolve(__dirname, "schema.graphql"),
"utf8"
)
createTypes(typeDefs)
}
# Define a common interface for all content block types; specify
# any fields that you want to query on the union directly here
interface ContentBlock {
title: String
}
# Explicitly implement the interface for each content block type
type SanityHero implements ContentBlock {
title: String
}
type SanityCarousel implements ContentBlock {
title: String
}
# Define a union of all of your content block types
union ContentBlocks = SanityHero | SanityCarousel
# Set the field type to an array of your union in any cases where
# you want to be able to query your shared fields at the top level
type SanityPage implements Node {
content: [ContentBlocks]
}
import React from "react"
import { graphql } from "gatsby"
const Page = props => <pre>{JSON.stringify(props, null, 2)}</pre>
export default Page
export const query = graphql`
{
sanityPage {
content {
...Blocks
...on SanityHero {
heroSpecificField
}
}
}
}
fragment Blocks on ContentBlock {
# shared fields
title
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment