DEV Community

Discussion on: Understanding GraphQL Mutations

Collapse
 
alexr89 profile image
Alex • Edited

Is it possible to return two "things" from a graphql mutation in like an or statement format?

For example, what if you wanted to return a song from addSong, or some sort of "customError" if say that song was already created?

The problem I see with a custom object like AddSongResponse, is that it cant be reused - it only applies to adding songs. If you had a customError , you could return this from say an addSong mutation, an addArtist mutation, an addAlbum mutation etc etc rather than individual objects for each mutation

Collapse
 
eveporcello profile image
Eve Porcello

Hey Alex - yeah absolutely. You can return whatever you want from a GraphQL mutation as long as you specify it in the schema. If you wanted to return a reusable object, that's totally doable!

This is a good article about some other options.

Collapse
 
alexr89 profile image
Alex • Edited

Thanks very much for the swift reply!

I had a look at the article you linked, but I seem to be struggling to understand how I return "this or that" from a mutation. My example is as follows:

I'd like to log a user in, and if the user doesn't exist, return a "Custom Error". In my head it would look something like this:

login(
password: String!
email: String!
): User || CustomError

Essentially, we return a User or a CustomError - these are both types defined in the schema. However, I don't know if this is possible (cant get it working at least!).

Tying the return of login down to a "LoginResponse" object feels wrong, because i'll need to have a "-InsertmutationNameHere-Response" object for every mutation. It seems better to have a system of "if we have data, return it or return CustomError" - if thats possible!

Thread Thread
 
eveporcello profile image
Eve Porcello • Edited

Oh gotcha! Look into union types. Unions allow you to return this or that and are often used with Error types.

Your example would probably look like this in the schema:

union LoginResult = User | CustomError

login(...): LoginResult
Enter fullscreen mode Exit fullscreen mode

The docs describe unions in more detail: graphql.org/learn/schema/#union-types
And Sasha Solomon has written about how she's used this pattern at Medium and Twitter: medium.com/@sachee/200-ok-error-ha...

Thread Thread
 
alexr89 profile image
Alex

Hey Eve, sorry for not replying. I got this working using your initial idea - returning a custom type :)