Explicitly Defining Data Types

In many Gatsby sites, we need to merge data from disparate sources and schemas into a synthesized GraphQL API that can be consumed from any Gatsby component. Standardizing discrete formats into a single schema supports long-term maintenance and a more efficient developer experience. Schema customization allows us to combine distinct data types into a cohesive schema—in fact, this is what Gatsby does through its source plugins when developers query data from multiple sources through the API.

Source and transformer plugins provide a means for Gatsby to recognize disparate data types. But these plugins in and of themselves don’t necessarily reformat the data entering GraphQL according to specifications we as Gatsby developers set. Take, for example, the following three documents, which represent a blog article, a list of authors of blog articles, and a list of translators of blog articles.

The first file is an example blog article formatted in Markdown, located at src/data/article-1.md:

---
title: Article one
date: 2020-04-19
author: [email protected]
translations:
  - English
---

# Lorem ipsum

Dolor sit amet.

The second file is a JSON list of authors that includes the author of this article:

// src/data/author.json
[
  {
   "name": "Baldwin",
   "firstName": "James",
   "email": "[email protected]",
   "created": "2018-09-02"
  },
  {
   "name": "Toklas",
   "firstName": "Alice",
   "email": "[email protected]",
   "created": "2016-03-23"
  }
]

The third file is a JSON list of translators, none of whom is referenced in the article:

// src/data/translator.json
[
  {
   "name": "wa Goro",
   "firstName": "Wangui",
   "email": "[email protected]",
   "multipleLanguages": true
  }
]

As we’ve seen in previous sections, we can immediately begin querying the data contained in these files by leveraging the gatsby-source-filesystem source plugin in conjunction with the gatsby-transformer-remark (Markdown) and gatsby-transformer-json (JSON) transformer plugins:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/data/`,
      },
    },
    `gatsby-transformer-remark`,
    `gatsby-transformer-json`,
  ],
}

Using these plugins out of the box and configured to pull from these directories results in a Node for each of these items of, respectively, type MarkdownRemark (Markdown), AuthorJson (JSON), and TranslatorJson (JSON).


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *