Let's imagine I have a createPost
mutation that inserts a new post. In a typical app, that mutation can either:
Post
.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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With