menu

Gatsby.js

Fast in every way that matters. Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps.

Channels
# All channels
view-forward
# General
view-forward
# I Made This
view-forward
# Meta
view-forward
# Themes
view-forward
Team

How to build GraphQL types on top of gatsby-transformer-remark?

May 5, 2020 at 1:19pm

How to build GraphQL types on top of gatsby-transformer-remark?

May 5, 2020 at 1:19pm (Edited 2 months ago)
I am looking to manipulate the frontmatter of MarkdownRemark nodes and create contextualized GraphQL types from them. My goal is to inherit the work gatsby-transformer-remark and associated plugins have performed on nodes, and then build on top of them. One example might be to process markdown within frontmatter properties. An added benefit of this is that the fields available in frontmatter would be specific to a set of markdown files, rather than having one generic MarkdownRemark type.

Working Example

I currently have a working example here, but it feels problematic for two reasons:
  1. The processing that gatsby-transformer-remark does after the onNodeCreate hook is not available on the object. For example, the html field won't exist on my inherited type.
  2. I can overcome the point above by setting the mediaType to that of the sourced file node, but then I can only get to the html property through childMarkdownRemark. That's not a huge problem, but it's indicative of a bigger problem, which is that I've just create another MarkdownRemark node on top of the node that was already processed, leading to duplicated nodes, and that feels like a major performance issue.

Another Approach

I've considered another approach that is to explicitly define the fields I want to add in the GraphQL schema. The problem with this approach is that I would have to know the type name for every object I want to manipulate, and that feels like it could be brittle. e.g. a frontmatter path to something like sidebar.content.features would be of type MarkdownRemarkFrontmatterSidebarContentFeature (or something like that). It feels like I'd be rewriting logic that already exists with Gatsby.
I've tried implicitly adding these fields by hooking into onNodeCreate for MarkdownRemark nodes, and adding properties to the node. That works when the server first boots up (and on build), but it doesn't work when changing markdown files on the fly (which is a requirement for me).
I'm curious what the community would consider best practice in approaching this problem?
No messages yet