Skip to content

Instantly share code, notes, and snippets.

@isramv
Created May 28, 2020 18:21
Show Gist options
  • Save isramv/a4f1acaf3db847f46a7812b9cd9d5994 to your computer and use it in GitHub Desktop.
Save isramv/a4f1acaf3db847f46a7812b9cd9d5994 to your computer and use it in GitHub Desktop.
gatsby-node.js
exports.onCreateNode = ({node, actions, getNodes, graphql, createNodeId, getCache}) => {
if (node.internal.type !== 'SitePage') {
return;
}
const {
createNode
} = actions
let media = []
async function getMediaById(id) {
const [ imgObj ] = await getNodes().filter(node => node.internal.type == 'CoolDrupalImage' && node.id == id)
// Fetch remote image.
const fileNode = await createRemoteFileNode({
url: imgObj.url,
parentNodeId: imgObj.id,
createNode,
createNodeId,
getCache
})
if (fileNode) {
imgObj.gatsbyImage = fileNode
media.push(imgObj)
}
Promise.resolve(imgObj)
return imgObj
}
if (_.has(node, 'context.body')) {
let rx = /\[media:([0-9]+)\]/g
async function replacer(match, mediaId) {
const img = await getMediaById(mediaId)
const imgUrl = img.url
const imgAlt = img.alt
return `![${imgAlt}](${imgUrl})`
}
stringReplaceAsync(node.context.body.value, rx, replacer).then((newMarkdown) => {
const md = newMarkdown
actions.createNode({
id: node.context.id,
parent: node.id,
content: md,
media: media,
internal: {
type: 'DrupalBlogPost',
contentDigest: node.internal.contentDigest
}
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment