Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL: how can I throw a warning after a successful mutation?

Tags:

graphql

apollo

Let's imagine I have a createPost mutation that inserts a new post. In a typical app, that mutation can either:

  • Succeed, returning a Post.
  • Fail, throwing an error (I use apollo-errors to handle this).

What I'd like to implement is a middle scenario, where the mutation succeeds (returning a Post); but also somehow returns a warning to the user (e.g. Your post is similar to post XYZ or similar).

What would be a good GraphQL pattern to implement this? Adding a warning field to the Post type seems a little weird, but then again I'm not sure how to return both a Post and a Warning in the same mutation? Any ideas?

(Note that I'm using this scenario as an example, I'm interested in the general pattern of returning extra post-mutation data, not finding similar posts specifically)

like image 362
Sacha Avatar asked Apr 17 '18 02:04

Sacha


1 Answers

All my mutations return a wrapping payload type rather than a single value type (e.g. Post in your case), I also don't ever throw in GraphQL unless it's a real system error -- if it's the consequence of user input or is an otherwise expected case, I model it into the return type.

Returning a wrapping payload is generally considered a best practice because a) your mutation should return entry points for everything in the graph that may have changed (not just the new post), and b) it gives you the easy ability to add new fields to the return type at a later time.

Remember, a mutation is essentially a function that takes in some input data and the current graph, and returns a new graph. It's generally a mistake to think in terms of REST-like CRUD operations.

type CreatePostError = {
    // Whatever you want
}

type CreatePostSuccess = {
    post: Post!
    warning: String
}

union CreatePostPayload = CreatePostSuccess | CreatePostError

mutation {
    // Other mutations
    createPost(/* args /*): CreatePostPayload
}
like image 132
Andrew Ingram Avatar answered Oct 16 '22 11:10

Andrew Ingram