1

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!

Art
  • 453
  • 4
  • 12
  • This is the section of the doc that's about mapping foreign-key fields: https://www.gatsbyjs.com/docs/reference/graphql-data-layer/schema-customization/#foreign-key-fields – LekoArts Feb 01 '21 at 08:29
  • @LekoArts Thanks. Don't think I understand the document enough to get it to work for me :P (get sth like `GraphQLError: Field "authors" of type "[Mdx]" must have a selection of subfields. Did you mean "authors { ... }"?`) I ended up doing something like [this](https://stackoverflow.com/a/65989605/3230090) which isn't ideal but it works. Would love to hear your thoughts. – Art Feb 01 '21 at 08:51

1 Answers1

2

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)
}
Art
  • 453
  • 4
  • 12