Skip to content

Commit

Permalink
fix: improved sourcing of remote image files (#3)
Browse files Browse the repository at this point in the history
* fix: remove use of depricated __NODE

* chore: add logging

* fix: move file creation to onCreateNode
  • Loading branch information
raae authored Feb 17, 2022
1 parent d2b5fc1 commit 751cba5
Showing 1 changed file with 36 additions and 11 deletions.
47 changes: 36 additions & 11 deletions plugin/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,35 +22,60 @@ const fetchEmbed = async (id) => {
const prepYouTubeNode = async (gatsbyUtils, id) => {
const {
actions: { createNode },
getCache,
createNodeId,
createContentDigest,
reporter,
} = gatsbyUtils;

const youTubeNodeId = createNodeId(`you-tube-${id}`);
const embedData = await fetchEmbed(id);

const imageFile = await createRemoteFileNode({
// The source url of the remote file
url: embedData.thumbnail_url,
parentNodeId: youTubeNodeId,
getCache,
createNode,
createNodeId,
});

createNode({
id: youTubeNodeId,
youTubeId: id,
oEmbed: embedData,
thumnail___NODE: imageFile.id,
internal: {
type: `YouTube`,
contentDigest: createContentDigest(embedData),
},
});

reporter.info(`Created YouTube Node for ${id}`);
};

exports.sourceNodes = async (gatsbyUtils, pluginOptions) => {
const { youTubeIds = [] } = pluginOptions;
await Promise.all(youTubeIds.map((id) => prepYouTubeNode(gatsbyUtils, id)));
};

exports.onCreateNode = async (gatsbyUtils) => {
const { node, actions, reporter, createNodeId, getCache } = gatsbyUtils;
const { createNodeField, createNode } = actions;

if (node.internal.type === `YouTube`) {
const imageFile = await createRemoteFileNode({
// The url of the remote file
url: node.oEmbed.thumbnail_url,
parentNodeId: node.id,
getCache,
createNode,
createNodeId,
});

createNodeField({
node,
name: `thumbnailFileId`,
value: imageFile.id,
});

reporter.info(`Created YouTube File Node for ${node.youTubeId} thumbnail`);
}
};

exports.createSchemaCustomization = ({ actions }) => {
actions.createTypes(`
type YouTube implements Node {
thumbnail: File @link(from: "fields.thumbnailFileId")
}
`);
};

0 comments on commit 751cba5

Please # to comment.