Skip to content

Instantly share code, notes, and snippets.

@Maxhodges
Created August 30, 2017 07:51
Show Gist options
  • Select an option

  • Save Maxhodges/45b92aa7a3a64a60ab57a2e940f23366 to your computer and use it in GitHub Desktop.

Select an option

Save Maxhodges/45b92aa7a3a64a60ab57a2e940f23366 to your computer and use it in GitHub Desktop.
const _ = require(`lodash`);
const Promise = require(`bluebird`);
const path = require(`path`);
const slash = require(`slash`);
// Implement the Gatsby API “createPages”. This is
// called after the Gatsby bootstrap is finished so you have
// access to any information necessary to programatically
// create pages.
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators;
// The “graphql” function allows us to run arbitrary
// queries against the local Contentful graphql schema. Think of
// it like the site has a built-in database constructed
// from the fetched data that you can run queries against.
return (
graphql(
`
{
allContentfulLandingPage(limit: 1000) {
edges {
node {
id
slug
}
}
}
}
`
)
.then(result => {
if (result.errors) {
throw new Error(
"GraphQL allContentfulLandingPage error #UfWvVV",
result.errors
);
}
// Create Product pages
const template = path.resolve(`./src/templates/landingPage.js`);
// We want to create a detailed page for each
// product node. We'll just use the Contentful id for the slug.
_.each(result.data.allContentfulLandingPage.edges, edge => {
// Gatsby uses Redux to manage its internal state.
// Plugins and sites can use functions like "createPage"
// to interact with Gatsby.
createPage({
// Each page is required to have a `path` as well
// as a template component. The `context` is
// optional but is often necessary so the template
// can query data specific to each page.
path: `/buy-japan/${edge.node.slug}/`,
component: slash(template),
context: {
id: edge.node.id
}
});
});
})
.then(() => {
return graphql(
`
{
allContentfulProduct(limit: 1000) {
edges {
node {
id
slug
}
}
}
}
`
);
})
// Product query result
.then(result => {
if (result.errors) {
throw new Error(
"GraphQL allContentfulProduct error #JPYS0x",
result.errors
);
}
// Create Product pages
const template = path.resolve(`./src/templates/product.js`);
// We want to create a detailed page for each
// product node. We'll just use the Contentful id for the slug.
_.each(result.data.allContentfulProduct.edges, edge => {
// Gatsby uses Redux to manage its internal state.
// Plugins and sites can use functions like "createPage"
// to interact with Gatsby.
createPage({
// Each page is required to have a `path` as well
// as a template component. The `context` is
// optional but is often necessary so the template
// can query data specific to each page.
path: `/product/${edge.node.slug}/`,
component: slash(template),
context: {
id: edge.node.id
}
});
});
})
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment