Created
September 15, 2020 18:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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