Gatsby's mapping between markdown files

387 views Asked by At

I'm creating a multi-author site (using gatsby-plugin-mdx) and have the following file structure:

/posts
- /post-1/index.mdx
- /post-2/index.mdx
- ...
/members
- /member-a/index.mdx
- /member-b/index.mdx
- ...

In the frontmatter of the post page I have an array of authors like

authors: [Member A, Member B]

and I have the name of the author in the frontmatter of the author's markdown file.

I'd like to set the schema up so that when I query the post, I also get the details of the authors as well (name, email, etc.).

From reading this page it seems like I need to create a custom resolver... but all the examples I see have all the authors in one json file (so you have two collections, MarkdownRemark and AuthorJson... while I think for my case all my posts and members are in MarkdownRemark collection.

Thanks so much!

1

There are 1 answers

0
Art On BEST ANSWER

I end up doing something like this. Surely there's a cleaner way, but it works for me. It goes through all the Mdx and add a field called authors, which is queried, to all Mdx types.

One problem with this is that there's also authors under members, which is not ideal. A better approach is to define new types and change Mdx in the last resolver to your new post data type. Not sure how to get that to work though. At the end, I could query something like:

query MyQuery {
  posts {
    frontmatter {
      title
      subtitle
    }
    authors {
      frontmatter {
        name
        email
      }
    }
  }
}
exports.createResolvers = ({ createResolvers }) => {
  const resolvers = {
    Mdx: {
      authors: {
        type: ["Mdx"],
        resolve(source, args, context, info) {
          return context.nodeModel.runQuery({
            query: {
              filter: {
                fields: {
                  collection: { eq: "members" }
                },
                frontmatter: {
                  memberid: { in: source.frontmatter.authors },
                },
              },
            },
            type: "Mdx",
            firstOnly: false,
          })
        }
      }
    },
  }
  createResolvers(resolvers)
}