Skip to content

Instantly share code, notes, and snippets.

@LawJolla
Last active June 25, 2018 18:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LawJolla/cbe74b53d9a4a3ec3282535f1d99e720 to your computer and use it in GitHub Desktop.
Save LawJolla/cbe74b53d9a4a3ec3282535f1d99e720 to your computer and use it in GitHub Desktop.
Gatsby + API / GraphQL Call
const GraphQLClient = require('graphql-request').GraphQLClient;
const crypto = require('crypto');
const path = require('path');
module.exports.sourceNodes = async ({ boundActionCreators }) => {
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