Skip to content

Commit

Permalink
Merge pull request gatsby-uc#286 from mwoelk/master
Browse files Browse the repository at this point in the history
Create nodes for media type (gatsby-uc#285)
  • Loading branch information
markkaylor committed Mar 18, 2022
2 parents 74e9f5c + e57c887 commit 2a60320
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,34 @@ const prepareTextNode = (text, ctx) => {
return textNode;
};

/**
* Create a child node for media and link the parent node to it
* @param {Object} media
* @param {Object} ctx
* @returns {Object} gatsby node
*/
const prepareMediaNode = (media, ctx) => {
const { createNodeId, createContentDigest, parentNode } = ctx;

const nodeType = 'STRAPI__MEDIA';
const relationNodeId = createNodeId(`${nodeType}-${media.id}`);

const node = {
...media,
id: relationNodeId,
strapi_id: media.id,
parent: parentNode.id,
children: [],
internal: {
type: nodeType,
content: JSON.stringify(media),
contentDigest: createContentDigest(media),
},
};

return node;
};

/**
* Returns an array of the main node and children nodes to create
* @param {Object} entity the main entry
Expand Down Expand Up @@ -251,6 +279,37 @@ export const createNodes = (entity, ctx, uid) => {

nodes.push(JSONNode);
}

if (type == 'media') {
const config = {
createContentDigest,
createNodeId,
parentNode: entryNode,
};

if (Array.isArray(value)) {
const mediaNodes = value.map((relation) => prepareMediaNode(relation, config));
entity[`${attributeName}___NODE`] = mediaNodes.map(({ id }) => id);

mediaNodes.forEach((node) => {
if (!getNode(node.id)) {
nodes.push(node);
}
});
} else {
const mediaNode = prepareMediaNode(value, config);

entity[`${attributeName}___NODE`] = mediaNode.id;

const relationNodeToCreate = getNode(mediaNode.id);

if (!relationNodeToCreate) {
nodes.push(mediaNode);
}
}
// Resolve only the attributeName___NODE and not to both ones
delete entity[attributeName];
}
}
}

Expand Down

0 comments on commit 2a60320

Please sign in to comment.