Skip to content

Instantly share code, notes, and snippets.

@disintegrator
Last active June 19, 2022 13:43
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disintegrator/b4cd67d667efeec784208763d9fe5b11 to your computer and use it in GitHub Desktop.
Save disintegrator/b4cd67d667efeec784208763d9fe5b11 to your computer and use it in GitHub Desktop.
Add a reading time estimate to all your Contentful rich text nodes in GatsbyJS
exports.onCreateNode = async options => {
return Promise.all([
require("./gatsby-onCreateNode-readingTime").onCreateNode(options)
// add your other onCreateNode functions here
]);
};
import { documentToPlainTextString } from "@contentful/rich-text-plain-text-renderer";
import readingTime from "reading-time";
import { GatsbyNode } from "gatsby";
export const onCreateNode: GatsbyNode["onCreateNode"] = async ({
node,
loadNodeContent,
actions
}) => {
const { internal } = node;
const { owner, mediaType } = internal;
if (mediaType !== "text/richtext" || owner !== "gatsby-source-contentful") {
return;
}
const doc = JSON.parse(await loadNodeContent(node));
const text = documentToPlainTextString(doc);
const result = readingTime(text);
actions.createNodeField({ node, name: "readingTime", value: result });
};
{
contentfulBlogPost {
body {
fields {
readingTime {
text
minutes
time
words
}
}
}
}
}
@rmcsharry
Copy link

Thank you for creating this gist, it was instrumental in getting this adding to my Gatsby site. Great gist!

@Draketheb4dass
Copy link

I get "SyntaxError: Unexpected token {" from gatsby-onCreateNode-readingTime.js

@tbrannam
Copy link

What version of gatsby-source-contentful are you using? I always get Error: Could not find function loadNodeContent for plugin gatsby-source-contentful on line 15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment