Skip to content

Instantly share code, notes, and snippets.

@jserrao
Last active November 25, 2018 03:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jserrao/eba996e946e48b00cc037e75567c520e to your computer and use it in GitHub Desktop.
Save jserrao/eba996e946e48b00cc037e75567c520e to your computer and use it in GitHub Desktop.
gatsby-node.js with DOM Parsing
// Give Node access to path
const path = require('path')
const fs = require('fs')
// Setup parser for taking apart the HTML Description hack stuff from Shopify
const DomParser = require('dom-parser')
const shopifyDescParser = new DomParser()
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
/**********************
PRODUCTS
***********************/
const getProducts = await graphql(`
{
allShopifyProduct {
edges {
node {
handle
title
productType
descriptionHtml
images {
localFile {
name
childImageSharp {
fluid(maxWidth: 800) {
aspectRatio
base64
sizes
src
srcSet
srcSetWebp
srcWebp
}
}
}
}
variants {
id
availableForSale
compareAtPrice
price
title
}
}
}
}
}
`)
// Creates individual products
getProducts.data.allShopifyProduct.edges.forEach(product => {
/**
* PARSE DESCRIPTION
* Shopify doesn't support custom fields in their API
* So we're hacking the description field with HTML to send structured metadata
* We take apart the the string, and then send it to components as part of pageContext
*
* fields-
* product-long-description
* product-short-description
* product-strain
* product-tac
*/
let shopifyDescFields = shopifyDescParser.parseFromString(product.node.descriptionHtml)
// Make product pages
createPage({
path: `/products/single/${product.node.handle}/`,
component: path.resolve('src/components/ProductSingle/productsingle.js'),
context: {
handle: product.node.handle,
id: product.node.id,
images: product.node.images,
longDescription: shopifyDescFields.getElementById('product-long-description').innerHTML,
productType: product.node.productType,
shortDescription: shopifyDescFields.getElementById('product-short-description').innerHTML,
strain: shopifyDescFields.getElementById('product-strain').innerHTML,
tac: `TAC: ${shopifyDescFields.getElementById('product-tac').innerHTML}`,
title: product.node.title,
variants: product.node.variants.map( ( singleVariant ) => {
return `${singleVariant.title} - $${singleVariant.price}`
})
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment