How I Automated My github Code to Gatsby Posts

Tue Sep 01 2020
  • My previous situation
  • Goal
  • Action
  • Outcome

My previous situation

As I moved my blog to Gatsby, I started adding more content to my site. So "normal" blog posts just like this one, its fine to manually upload as I need to write it down first. The problem was that I was solving algorithm exercises either on LeetCode, HackerRank or other. I would upload the code my github repo and then I'll need to go to my blog and write a blog post. The rate of me solving problems was much faster of me uploading the blog content.

Goal

I would like to be able to upload my algorithm solutions, add some readme doc and then it will automatically create a new blog post on my blog.

Action

I would first need to decide on a "template" for my readme page, so I'll know how to build the blog post on my site. After that I altered my Gatsby site, to load my Github repo files. It will look for readme file with a specific template and if it find those, it will create a blog post with that content.

Outcome

Everytime I solve a new exercise and want to have a blog post for it, I just create the readme file. Push the code and post gets created on my site.

Actions Steps on Gatsby

  • add this config to gatsby-config.js
{
  resolve: `gatsby-source-git`,
  options: {
    name: `challenges`,
    remote: `https://github.com/tzookb/programming-challenges.git`,
    patterns: [`exercises/**/*.md`]
  }
},
  • add product creation in gatsby-node.js
  • I wont share all the page creation as its a bit big
  • but the relevant Graphql query is this:
  const result = await graphql(`
    {
      allFile(
        filter: { sourceInstanceName: { eq: "challenges" } },
        limit: 10000,
        sort: {order: ASC, fields: [childMdx___frontmatter___date]}
      ) {
        edges {
          node {
            relativePath
            childMarkdownRemark {
              frontmatter {
                title
                url
                desc
                date
                source
              }
              html
            }
          }
        }
      }
  `)

I look up all the files (only readmes, from config) and take the details I need for creating the post page.

just go to the home page and look up any LeetCode or HackerRank exercises :)