Gatsby: [gatsby-transformer-remark] Is there a way to access node.html in onCreateNode?

Created on 24 Aug 2019  路  6Comments  路  Source: gatsbyjs/gatsby

Summary

node.html of MarkdownRemark nodes are undefined in onCreateNode. Is there a way to access it?

Relevant information

There are some relevant issues: #2991 #6314, but both of them are not resolved and closed.

Environment (if relevant)

Irrelevant.

File contents (if changed)

gatsby-config.js: N/A
package.json: N/A
gatsby-node.js:

exports.onCreateNode = async ({ node }) => {
  if (node.internal.type === 'MarkdownRemark') {
    console.log(typeof node.html) // => undefined
  }
}

gatsby-browser.js: N/A
gatsby-ssr.js: N/A

question or discussion

Most helpful comment

@Chalarangelo Here is a better way to get the resolver:

// gatsby-node.js
exports.createResolvers = await ({ createResolvers }) => createResolvers({
  SomeType: {
    someField: {
      resolve: async (source, _, context, info) => {
        const resolver = info.schema.getType("MarkdownRemark").getFields()["tableOfContents"].resolve
        const node = await context.nodeModel.getNodeById(id)
        const args = {} // arguments passed to the resolver
        const toc = await resolver(node, args)
        return toc
      }
    }
  }
})

All 6 comments

gatsby-transformer-remark generates the html from markdown not immediately when creating the MarkdownRemark nodes, but lazily when the html field resolver is called in a query. This means that the html is not yet available in onCreateNode.

What are you trying to achieve? There might be another way to do it.

@stefanprobst I am trying to encrypt the html in a new node, and then decrypt in the browser.

I found a tricky solution: create a resolver for the encrypted field, and use nodeModel.runQuery in the resolver with a filter on html field to force html to be resolved.

cool, great solution! :+1:

@problem233 Can you provide a sample of the code? I want to do something reasonably similar in my project.

@Chalarangelo Here is a better way to get the resolver:

// gatsby-node.js
exports.createResolvers = await ({ createResolvers }) => createResolvers({
  SomeType: {
    someField: {
      resolve: async (source, _, context, info) => {
        const resolver = info.schema.getType("MarkdownRemark").getFields()["tableOfContents"].resolve
        const node = await context.nodeModel.getNodeById(id)
        const args = {} // arguments passed to the resolver
        const toc = await resolver(node, args)
        return toc
      }
    }
  }
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

KyleAMathews picture KyleAMathews  路  3Comments

kalinchernev picture kalinchernev  路  3Comments

benstr picture benstr  路  3Comments

andykais picture andykais  路  3Comments

rossPatton picture rossPatton  路  3Comments