aofolts
12/4/2018 - 12:34 AM

Gatsby / Contentful — createPages

Create Contentful pages from data (supports multiple entry types).

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

  const createPages = new Promise((resolve,reject) => {
    resolve(
      graphql(
        `
          {
            pages: allContentfulPage {
              edges {
                node {
                  slug
                }
              }
            }
          }
        `
      ).then(({
        errors,
        data
      }) => {
        if (errors) {
          console.log(errors)
          reject(errors)
        }

        const pages = data.pages.edges.map(entry => entry.node)
        
        pages.forEach(entry => {
          let slug = entry.slug

          createPage({
            path: slug === `home` ? '/' : `/${slug}/`,
            component: templates[slug] || templates.page,
            context: {
              slug
            }
          })
        })
      })
    )
  })

  return Promise.all([
    createPages
  ])
}