Adding Markdown Posts to your Data Layer

dorf8839

Cory Dorfner

Posted on November 3, 2022

Adding Markdown Posts to your Data Layer

Hello and welcome to the third post in my series on Building a Powerful Blog!🎉 So far, you've created your Gatsby site and deployed it for the world to see using Netlify. You've also learned about the power of Markdown for writing your blog posts and have created a blog post of your own. If you haven't already, I would recommend going back to the first post of the series, Creating a Gatsby Blog Site, to get caught up before continuing.

Now it's time to learn how to store your Markdown blog post, and the many to come, directly in your own codebase and add them to your GraphQL data layer in Gatsby. These steps will allow you to easily add and maintain your blog posts, while reducing code duplication and simplifying the process for pulling the content into your website. I hope you're as excited to get started as I am!🥳


Storing Your Blog Posts

Storing the content of your blog posts within your site is as quick and easy as adding in a folder and moving any content already created into specific folders for each post. That's it; that's all there is to it.

We'll start by locating the src folder in the root directory of your codebase. When you have find it, right-click on the folder and select the New Folder... option. Give this new folder the title of "posts". Next, we're going to create another folder within the newly created "posts" folder. These subfolders are needed in the case that you would also like to include images with your blog posts. While we could store these images elsewhere and simply reference them in the post, I've found this way to be cleaner for keeping everything organized. With this new folder, you can title it how ever you see fit. For the purposes of this post, we'll give it the name of "My First Blog Post".

Within this subfolder is where we will store the markdown file itself, as well as any related images or files. To create a new file, right-click on the "My First Blog Post" folder and select New File... from the menu. When the new file is created, you again can give it whichever title best suites your needs. Just be sure the extension of the file is .md. Again, we'll give this new file the title of "My First Blog Post.md" for the purposes of this blog post. At this point, you can add in your YAML frontmatter and blog post content, chocked full of your knowledge and teachings for others to enjoy. If you haven't already, you can read up on how to format your content from my previous article, Writing Posts in Markdown

Now that we have your post added into your codebase, we can utilize GraphQL to retrieve the data and content from within your files!

Napoleon Dynamite Yes Reaction GIF


Adding To Your GraphQL Data Layer

GraphQL is a powerful query language, providing a complete and understandable description of the data in your API, and a quick runtime for fulfilling those queries with your existing data. Gatsby utilizes its own GraphQL data layer to store all of the data for your site, whether that's in your codebase's filesystem, a content management system like WordPress, or even a database. The data is retrieved from these different sources using specific source plugins.

We've already installed the necessary source plugin for retrieving data from your filesystem during the creation of the site, gatsby-source-filesystem. When the site is being built, this plugin will pull the data from your filesystem and add it directly into your site's GraphQL data layer. To get the data back out of the data layer, we'll write GraphQL queries to retrieve the data and provide it as objects to the templates we'll create later on. First things first though, let's create the needed queries to retrieve your blog post content.

Before we can get started, we need to make one quick change to the "gatsby-config.js" file that was created with the site. Within your IDE, go to the root folder of your directory and open it up. In this file, you'll find an array of plugins being exported. Find the gatsby-source-filesystem objects in the array; there should be two. Below the second object, we're going to add another of these objects to target our folder of markdown files:

module.exports = {
  siteMetadata: {
    title: `Personal Website`,
    siteUrl: `https://www.yourdomain.tld`
  },
  plugins: ["gatsby-plugin-image", "gatsby-plugin-sitemap", 
  ...
  }, {
    resolve: "gatsby-source-filesystem",
    options: {
      path: `${__dirname}/src/posts`,
      name: "posts"
    }
  }]
};
Enter fullscreen mode Exit fullscreen mode

These configuration options will add all of the files in the folder, specified by the path option, into your data layer. The __dirname section of the path string is a variable from Node.js that stores the absolute path for the directory that contains the file currently being run. This will ensure that the correct folder is being pulled from each time. The name option gets set to the sourceInstanceName field for each file, allowing you to source files from multiple folders, if necessary. By providing a different name option for each gatsby-source-filesystem configuration object, you can build GraphQL queries that filter down to a specific folder.

After you have saved this file, start your local development server using npm run develop in your terminal. If the server is already running, be sure to stop it with ctrl+c and then start it back up again. This will ensure your new configuration changes are picked up by the server and will add the files to your data layer. Next comes the fun part of querying your data layer using GraphiQL. This is an incredibly useful tool from Gatsby to help you test out your GraphQL queries before adding them to you code, ensuring the request always responds with the data you expect.

Once the codebase has been built and the server is up and running, go to http://localhost:8000/___graphql in a new tab of your browser. There's three underscores in the URL so be sure to include three in yours as well. Navigating to that URL will display the following page:

Screenshot of the GraphQL page with a basic query and results

I've selected some basic fields from the Explorer column on the left panel to create the query in the center panel. From the Explorer column, you can toggle the dropdowns to expand the different fields that are available in the data layer. Blue items correlate to the data you can query for, while purple items correlate to arguments that can be used to filter the data. After clicking the "play" button at the top of the page, the results of the query are displayed in the right panel. Those are the basic steps to retrieving your data from the data layer but, if you would like to know more about Gatsby's GraphiQL, I would recommend viewing their GraphQL Data Layer overview.

To request all Markdown files from your data layer, we're going to use the allMarkdownRemark field. Feel free to explore the different fields within this dropdown to see what data you can get back from your content. Once ready, build the below query, using related fields in the Explorer panel or copying my query directly into your center panel, to get the path of all Markdown files in your posts folder:

query MyQuery {
  allMarkdownRemark(
    sort: {order: DESC, fields: frontmatter___dateEdited}
    limit: 1000
  ) {
    edges {
      node {
        frontmatter {
          path
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

After running the query, your response should look similar to the object below:

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "frontmatter": {
              "path": "/my-first-blog-post"
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}
Enter fullscreen mode Exit fullscreen mode

That's all there is to it! You now have your blog post added into the GraphQL data layer and can retrieve it in GraphiQL! I can't say it enough though, I would highly recommend reading through Gatsby's GraphQL Data Layer, as well as their GraphiQL How-To Guide. These sources will greatly help you better understand how to work with this tool, as well as GraphQL itself.


In the next post, we will continue working within the codebase to build pages from your blog posts using only one template file. That's right! One file will be used to create individual web pages for each blog post you have in your "posts" folder. I hope you enjoyed this post and found it's content helpful as you continue your journey through web development! The links to my social media accounts can be found on the contact page of my website. Please feel free to share any of your own experiences on working with GraphQL, general questions and comments, or even other topics you would like me to write about. Thank you and I look forward to hearing from you!👋

💖 💪 🙅 🚩
dorf8839
Cory Dorfner

Posted on November 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related