Skip to content

Instantly share code, notes, and snippets.

@JacobKnaack
Last active February 15, 2019 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JacobKnaack/692d2e93d3892ca2f1cd827d2a966a94 to your computer and use it in GitHub Desktop.
Save JacobKnaack/692d2e93d3892ca2f1cd827d2a966a94 to your computer and use it in GitHub Desktop.
Final gatsby-node
require("dotenv").config();
const path = require('path');
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions
deletePage(page)
createPage({
...page,
context: {
writeKey: `${process.env.COSMIC_WRITE_KEY}`,
readKey: `${process.env.COSMIC_READ_KEY}`,
cosmicBucket: `${process.env.COSMIC_BUCKET}`
}
})
}
// Gatsby's built in createPages API lets you
// explicitly create a page route from a template
exports.createPages = ({ graphql, actions }) => {
const { createPage, createRedirect } = actions
// configures our route and redirect slug
createRedirect({
fromPath: `/doc/*`,
isPermanent: true,
redirectInBrowser: true,
toPath: `/`,
})
// This promise makes a graphql request and builds
// a page using the returned data and our docTemplate
return new Promise((resolve, reject) => {
const docTemplate = path.resolve(`src/templates/docPage.js`)
resolve(
graphql(`
query {
docs {
objectsByType(bucket_slug: "${process.env.COSMIC_BUCKET}", type_slug: "docs", read_key: "${process.env.COSMIC_READ_KEY}") {
title
}
}
}
`
).then(result => {
if (result.errors) {
reject(result.errors)
}
result.data.docs.objectsByType.forEach(doc => {
let slug = doc.title.toLowerCase().replace(/\s/g, '-')
createPage({
path: `/doc/${slug}`,
component: docTemplate,
context: {
cosmicBucket: `${process.env.COSMIC_BUCKET}`,
readKey: `${process.env.COSMIC_READ_KEY}`,
title: slug,
}
})
})
})
)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment