Last active
January 25, 2019 01:17
-
-
Save mgmolisani/aafbf9d0ce6ee341df1046fa1fae1cb5 to your computer and use it in GitHub Desktop.
gatsby-node.js for Contentful richTextAST GraphQL node
This file contains 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 { GraphQLJSON } = require('gatsby/graphql'); | |
/* | |
I don't think we need to pathPrefixCacheStr this. | |
I would expect path prefixing to happen at the sourceNodes call and we are | |
parsing it's internal content which would have the prefixed changes. | |
New changes should change the digest in the sourceNodes call. | |
*/ | |
const richTextASTCacheKey = node => | |
`source-contentful-rich-text-AST-${node.internal.contentDigest}`; | |
exports.setFieldsOnGraphQLNodeType = ({ type, cache }) => { | |
const getRichTextAST = async richTextNode => { | |
const cachedRichTextAST = await cache.get( | |
richTextASTCacheKey(richTextNode) | |
); | |
if (cachedRichTextAST) { | |
return cachedRichTextAST; | |
} | |
const richTextAST = JSON.parse(richTextNode.internal.content); | |
/* | |
For some horrible reason, Gatsby uses a package for caching that says it resolves with the set value, but it | |
actually does not... | |
So we await the value to make sure something stores, and dangerously assume it is our content... | |
Then we return the content we sent... | |
*/ | |
await cache.set(richTextASTCacheKey(richTextNode), richTextAST); | |
return richTextAST; | |
}; | |
if (type.name.match(/contentful.*RichTextNode/)) { | |
return { | |
richTextAST: { | |
type: GraphQLJSON, | |
resolve: richTextNode => { | |
return getRichTextAST(richTextNode); | |
} | |
} | |
}; | |
} | |
return {}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment