Skip to content

Instantly share code, notes, and snippets.

@LawJolla
Created September 9, 2017 16:08
Show Gist options
  • Save LawJolla/58ac419472aa3c94ffa1c2068edb193d to your computer and use it in GitHub Desktop.
Save LawJolla/58ac419472aa3c94ffa1c2068edb193d to your computer and use it in GitHub Desktop.
Gatsby + GraphQL for Gatsby-node
const GraphQLClient = require('graphql-request').GraphQLClient;
const crypto = require('crypto');
const path = require('path');
module.exports.sourceNodes = async (
{ boundActionCreators, getNode, hasNodeChanged },
{ endpoint, token }
) => {
const { createNode } = boundActionCreators
const client = new GraphQLClient(process.env.GRAPHCOOL_API)
const data = await client.request(vehicles)
createNodes(createNode, data.allDealerships[0].inventory)
return false;
}
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
const template = path.resolve('src/templates/car.js');
resolve(
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(' ')[0]}`,
component: template,
context: {
slug: `${fields.make.split(' ')[0]}`,
fields
}
})
})
return
})
)
})
}
function createNodes(fn, nodes) {
//console.log('n',nodes);
nodes.forEach((node, i) => {
const jsonNode = JSON.stringify(node);
//console.log('vehicle node', jsonNode);
fn({
id: node.id,
parent: "Parent "+i,
field: jsonNode,
children: [],
internal: {
type: 'VehiclePage',
content: jsonNode,
contentDigest: crypto.createHash(`md5`).update(jsonNode).digest(`hex`)
}
})
})
}
const vehicles = `
{
allDealerships(filter:{ name:"Wheel Kinetics"}) {
inventory {
id
year
make
model
}
}
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment