REST API relation types are `string|Type` but always(?) `Type`

default discord avatar
schwartzmj12 months ago
2

I'm testing out PayloadCMS for our projects. I've noticed that when I do a query for, say, a Post that has a

featuredImage

(relation to another collection type) that the API response is always the Media type and never a

string

which I assume means its either an

id

or the object itself.



This feels... not great? Are there best practices to know what I'm getting or asking for one way or another?



According to the types, presumably I'd have to check if each relation is a string or not and then go fetch the asset if it is a string, which seems a bit ridiculous



Is the real recommended method to use GraphQL and some sort of codegen instead of REST?

  • discord user avatar
    jarrod_not_jared
    12 months ago

    Yes that is what you need to do if you truly want type safety. A few things are responsible for a string being returned, access control and depth being the most common. If you query a document with the query param

    ?depth=0

    all relationship fields on the doc will return only the ID. If the user requesting does not have access to the doc, the ID will return.



    Here is a way to type guard, but you would still want to handle cases where only an ID is returned:

    https://discord.com/channels/967097582721572934/1061947681448153188/1062007726537986138
  • default discord avatar
    schwartzmj12 months ago

    thank you, i'll look into it



    @jarrod_not_jared I should ask... do you have a recommendation for a package or set of packages to introspect the GraphQL endpoint and generate a type-safe client?



    I've set that up a long time ago for some other project but can't really recall what I used

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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