Skip to content

Instantly share code, notes, and snippets.

@LawJolla
Created September 18, 2017 05:15
Show Gist options
  • Save LawJolla/1dec210e5812604aaad67780bab62f35 to your computer and use it in GitHub Desktop.
Save LawJolla/1dec210e5812604aaad67780bab62f35 to your computer and use it in GitHub Desktop.
Gatsby Create pages from API
// Lightweight GraphQL generic client
const GraphQLClient = require('graphql-request').GraphQLClient;
const crypto = require('crypto');
const path = require('path');
const api = require('./api_constants');
//GraphQL query string to get all inventory, filtering by a specific dealer
const vehicles = `
{
allDealerships(filter:{ name:"Wheel Kinetics"}) {
inventory {
id
year
make
model
stockNo
}
}
}
`
// sourceNodes is a Gatsby API
module.exports.sourceNodes = async ({ boundActionCreators }) => {
const { createNode } = boundActionCreators
const client = new GraphQLClient(api.development.main)
const data = await client.request(vehicles)
// Passes inventory array of objects to createNodes function
// a node is created for each vehicle
createNodes(createNode, data.allDealerships[0].inventory)
}
// called after sourceNodes
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
const template = path.resolve('src/templates/car.js');
resolve(
// query Gatbsy's GraphQL store for all vehiclePage nodes
graphql(`
{
allVehiclePage(limit: 500) {
edges {
node {
field
}
}
}
}
`)
.then(result => {
if (result.errors) {
reject(result.errors);
}
result.data.allVehiclePage.edges.forEach(edge => {
const fields = JSON.parse(edge.node.field);
createPage({
path: `${fields.make.split(' ').join('-')}-${fields.stockNo}`,
component: template,
context: {
slug: `${fields.make.split(' ').join('-')}-${fields.stockNo}`,
fields
}
})
})
})
)
})
}
function createNodes(fn, nodes) {
nodes.forEach(node => {
const jsonNode = JSON.stringify(node);
fn({
id: node.id,
parent: null,
field: jsonNode, // pass queried data into node
children: [],
internal: {
type: 'VehiclePage',
content: jsonNode,
contentDigest: crypto.createHash(`md5`).update(jsonNode).digest(`hex`)
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment