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

筅森魡賤 提交于 2021-01-22 03:19:17

问题


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)


回答1:


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
}


来源:https://stackoverflow.com/questions/49868843/graphql-how-can-i-throw-a-warning-after-a-successful-mutation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!