Graphql Union using generated types

default discord avatar
emmanuel
3 weeks ago
8

Do you have a simple example of how to create a Graphql union with the types generated by Payload?

  • default discord avatar
    noheadphones
    3 weeks ago

    What are you trying to get exactly? It might be easier to recommend something with the full picture

  • default discord avatar
    emmanuel
    2 weeks ago

    So we have 3 schemas (collections), blogs, podcasts and videos, all of them shared common fields, so I want to create a union type/schema (e.g. type Post = Blog | Podcast | Video) so it can be exposed in the graphql api url and consumed by client.

  • default discord avatar
    noheadphones
    2 weeks ago

    You would have to make a new custom graphql endpoint



    and construct a new type for yourself using the graphQL object passed via the handler with

    https://graphql.org/graphql-js/type/#graphqluniontype


    something akin to


    new GraphQL.GraphQLUnionType()


    for the types you can get the generated ones from your

    payload.collections['blog'].graphQL.types

    instance to use as types here


    types: [DogType, CatType],


    I wrote a guide here on how to extend the graphql API

    https://nouance.io/articles/how-to-extend-graphql-in-payload-with-custom-queries-mutations-and-re-usable-types


    Here's the guide in payload docs

    https://payloadcms.com/docs/graphql/extending
Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.