Skip to content

Instantly share code, notes, and snippets.

@uokesita
Last active August 11, 2020 10:27
Show Gist options
  • Save uokesita/af769e50ac716bd909fb4583d476d74f to your computer and use it in GitHub Desktop.
Save uokesita/af769e50ac716bd909fb4583d476d74f to your computer and use it in GitHub Desktop.
Gatsby + Netlify CMS: One to Many relation
- name: "expertise"
label: "Expertise"
folder: "src/pages/expertise"
create: true
fields:
- {label: "Kind", name: kind, widget: hidden, default: "expertise"}
- {label: "Title", name: title, widget: string}
- {label: "Image", name: image, widget: image}
- name: "experts"
label: "Expert"
folder: "src/pages/experts"
create: true
fields:
- {label: "Kind", name: kind, widget: hidden, default: "expert"}
- {label: "Title", name: title, widget: string}
- {label: "Position", name: position, widget: string}
- {label: "LinkedIn Link", name: linkedinlink, widget: string}
- {label: "Twitter Link", name: twitterlink, widget: string}
- {label: "External Link", name: externallink, widget: string}
- {label: "Image", name: image, widget: image}
- label: "Expertise"
name: "expertise"
widget: "relation"
multiple: true
collection: "expertise_en"
searchFields: ["title"]
valueField: "title"
displayFields: ["title"]
- {label: "Description", name: description, widget: markdown}
plugins: [
...
],
mapping: {
'MarkdownRemark.fields.expertises': `MarkdownRemark`
}
...
exports.sourceNodes = ({ boundActionCreators, getNodes, getNode }) => {
const { createNodeField } = boundActionCreators
const expertiseOfExperts = {}
const getExpertiseNodeByName = name => getNodes().find(
node_ =>
node_.internal.type === `MarkdownRemark` &&
node_.frontmatter.title === name
)
getNodes()
.filter(node => node.internal.type === `MarkdownRemark`)
.forEach(node => {
if (node.frontmatter.kind == 'expert') {
const expertiseNodes = node.frontmatter.expertise instanceof Array
? node.frontmatter.expertise.map(getExpertiseNodeByName)
: [getExpertiseNodeByName(node.frontmatter.expertise)]
expertiseNodes.filter(authorNode=> authorNode).map(authorNode => {
if (!(node.id in expertiseOfExperts )) {
expertiseOfExperts[node.id] = []
}
expertiseOfExperts[node.id].push(authorNode.id)
})
}
})
Object.entries(expertiseOfExperts).forEach(([expertNodeId, expertiseIds]) => {
createNodeField({
node: getNode(expertNodeId),
name: `expertises`,
value: expertiseIds,
})
})
}
query MyQuery {
allMarkdownRemark(sort: {order: ASC, fields: [frontmatter___order]}, filter: {frontmatter: {kind: {eq: "expert"}}}) {
edges {
node {
frontmatter {
title
position
linkedinlink
twitterlink
externallink
expertise
}
fields {
expertises {
id
frontmatter {
title
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment