const path = require('path')
const { createFilePath } = require(`gatsby-source-filesystem`)

// To add the slug field to each post
exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions

  // Ensures we are processing only markdown files
  if (node.internal.type === 'MarkdownRemark') {
    const slug = createFilePath({
      node,
      getNode,
      basePath: 'pages',
    })

    // Creates new query'able field with name of 'slug'
    createNodeField({
      node,
      name: 'slug',
      value: `/${slug.slice(12)}`,
    })
  }
}

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  return graphql(`
    query {
      allMarkdownRemark(sort: { fields: frontmatter___date, order: DESC }) {
        edges {
          node {
            fields {
              slug
            }
          }
          next {
            frontmatter {
              title
            }
            fields {
              slug
            }
          }
          previous {
            frontmatter {
              title
            }
            fields {
              slug
            }
          }
        }
      }
    }
  `).then(result => {
    const posts = result.data.allMarkdownRemark.edges

    posts.forEach(({ node, next, previous }) => {
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/blogPost.js'),
        context: {
          slug: node.fields.slug,
          previousPost: previous,
          nextPost: next,
        },
      })
    })

    const postsPerPage = 6
    const numPages = Math.ceil(posts.length / postsPerPage)

    Array.from({ length: numPages }).forEach((_, index) => {
      createPage({
        path: index === 0 ? '/' : `page/${index + 1}`,
        component: path.resolve('./src/templates/blogList.js'),
        context: {
          limit: postsPerPage,
          skip: index * postsPerPage,
          numPages,
          currentPage: index + 1,
        },
      })
    })
  })
}

@@ -22,16 +22,44 @@
 'path')%0A
+const _ = require('lodash')%0A
 const %7B 
@@ -721,16 +721,29 @@
  %7B%0A     
+ postsRemark:
  allMark
@@ -1209,24 +1209,156 @@
   %7D%0A      %7D%0A
+      tagsGroup: allMarkdownRemark(limit: 2000) %7B%0A        group(field: frontmatter___tags) %7B%0A          fieldValue%0A        %7D%0A      %7D%0A
     %7D%0A  %60).t
@@ -1403,27 +1403,21 @@
 lt.data.
-allMarkdown
+posts
 Remark.e
@@ -2179,20 +2179,302 @@
    %7D)%0A    %7D)
+%0A%0A    const tags = result.data.tagsGroup.group%0A%0A    tags.forEach(tag =%3E %7B%0A      createPage(%7B%0A        path: %60/tags/$%7B_.kebabCase(tag.fieldValue)%7D/%60,%0A        component: path.resolve('src/templates/tags.js'),%0A        context: %7B%0A          tag: tag.fieldValue,%0A        %7D,%0A      %7D)%0A    %7D)
 %0A  %7D)%0A%7D%0A

Create tags pages