question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is there a way to query/gain access to other markdown files/nodes when resolving a Graphql query?

See original GitHub issue

Is there a way to query/gain access to other markdown files/nodes when resolving a Graphql query?

I have pages as markdown files with a front matter field for a list of widget names. These widgets are markdown files of their own with a bunch of front-matter fields that I will use as props in a react component.

I have all of the widgets in a separate folder and am not directly using them to create pages. What I would like to do is create a query that functions like this:

{
    allMarkdownRemark(filter: { fileAbsolutePath: {regex : "/src\/pages/"} }) {
        edges {
            node {
                excerpt(pruneLength: 400)
                html
                id
                frontmatter {
                    templateKey
                    path
                    date
                    title
                    // This frontmatter widgetlist has the names of the markdown files that I need to resolve the widgetList on the node.
                    widgetList {
                        widget 
                    }
                }
                widgetList {
                    widget {
                        widgetStyle
                        isCenter
                        isFullWidth
                    }
                }
            }
        }
    }
}

I am currently stuck because I have the names of the widgets that are supposed to be on each page in the front matter, but to resolve the widgetList type, I need to to find the markdown nodes in question in the page-components folder.

I used the code from gatsby-transformer-remark to get started creating my custom plugin in plugins/markdown-extender. Gatsby-transformer-remark has a file extend-node-type.js which I have been modifying. But a lot of this code is completely foreign to me other than the Graphql bits. @KyleAMathews would you be able to shed some light on this so I can start digging in a better direction? That would be much appreciated!

Here’s a link to the repo: https://github.com/luczaki114/Lajkonik-Gatsby-NetlifyCMS-Site

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:15 (11 by maintainers)

github_iconTop GitHub Comments

20reactions
piehcommented, Jan 26, 2018

Oh, we currently only map to ids. But we can make it work with some additional custom code in gatsby-node.js:

// we use sourceNodes instead of onCreateNode because at this time plugins
// will have created all nodes already and we can link both books to authors
// and reverse link on authors to books
exports.sourceNodes = ({ boundActionCreators, getNodes, getNode }) => {
  const { createNodeField } = boundActionCreators

  const booksOfAuthors = {}
  // iterate thorugh all markdown nodes to link books to author
  // and build author index
  const markdownNodes = getNodes()
    .filter(node => node.internal.type === `MarkdownRemark`)
    .forEach(node => {
      if (node.frontmatter.author) {
        const authorNode = getNodes().find(
          node2 =>
            node2.internal.type === `MarkdownRemark` &&
            node2.frontmatter.title === node.frontmatter.author
        )

        if (authorNode) {
          createNodeField({
            node,
            name: `author`,
            value: authorNode.id,
          })

          // if it's first time for this author init empty array for his books
          if (!(authorNode.id in booksOfAuthors)) {
            booksOfAuthors[authorNode.id] = []
          }
          // add book to this author
          booksOfAuthors[authorNode.id].push(node.id)
        }
      }
    })

  Object.entries(booksOfAuthors).forEach(([authorNodeId, bookIds]) => {
    createNodeField({
      node: getNode(authorNodeId),
      name: `books`,
      value: bookIds,
    })
  })
}

and in your gatsby-config.js use this mapping config:

  mapping: {
    'MarkdownRemark.fields.author': `MarkdownRemark`,
    'MarkdownRemark.fields.books': `MarkdownRemark`,
  },

and example query:

{
  markdownRemark(frontmatter: {title: {eq: "New Beginnings"}}) {
    id
    frontmatter {
      title
    }
    # author 
    fields {
      author {
        frontmatter {
          title
        }
        # all books of author
        fields {
          books {
            frontmatter {
              title
            }
          }
        }
      }
    }
  }
}
7reactions
piehcommented, Jan 26, 2018

There’s always room for improvement for sure. I’m currently working on schema related things and will add this to my list (why that list is only growing and not getting smaller 😠 ).

Way to to be able to specify on what field to we should link nodes would indeed be great as current mapping is best suited for json/yaml data (where we define id ourselves) or for programmatic solution (like one I pasted above). It would be great to do something like:

'MarkdownRemark.fields.author': {
  type: `MarkdownRemark`,
  fieldToJoinOn: 'frontmatter.title'
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Resolvers - Apollo GraphQL Docs
We want to define resolvers for the numberSix and numberSeven fields of the root Query type so that they always return 6 and...
Read more >
Advanced GraphQL Usage In Gatsby Websites
At this point, we can implement the createPages API to query for all markdowns and create a page with the path as the...
Read more >
How to solve GraphQL error when no markdown file is ...
I have this query on my Gatsby site. export const query = graphql` query MyBlogs { allMarkdownRemark(sort: { fields: frontmatter___date, ...
Read more >
Part 4: Query for Data with GraphQL
How do you get data back out of the data layer? You can write GraphQL queries inside of your components to pull out...
Read more >
Data fetching with Gatsby and GraphQL
Use GraphQL to fetch data from a Gatsby configuration and different sources including the file system, external APIs, databases, and CMSs.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found