如何在使用 graphql 插入之前执行更新插入或检查子查询的结果

How to do an upsert or check results of a sub query before inserting using graphql

我需要做本质上是 upsert 的事情。检查现有用户并进行一个突变与另一个突变的有效方法是什么。在我的例子中,如果用户存在,我需要进行登录,否则我应该在登录之前调用创建。我正在使用 graph.cool graphql 服务。我可以将它作为 2 个单独的调用来完成,但是有没有一种方法可以在 graphql 中编写它,以便它在一次调用中完成并且不需要第二次往返?请注意,我无法控制后端,只能使用现有的功能。

https://docs.graph.cool/reference/simple-api/user-authentication

mutation {

  // Only create a user if they do not exist already
  // is there a way to do a conditional statement in graphql here?
  createUser(authProvider: { auth0: { idToken: "<idToken>" }}) {
    id
  }

  // always try signing the user in with the token we already got from auth0
  signinUser(input: { auth0: { idToken: "<idToken>" }}) {
    id
    token
  }

}

我认为你的问题可以归结为 "how can I return either a token or an id depending on what the back end decided to do?"

答案是:a union type.

union authResult = id | token

mutation {
  authenticateUser(authProvider: { auth0: { idToken: "<idToken>" }}) {
    authResult
  }
}

现在你已经将"signin or create?"的决定延迟到后端,你可以一次完成并找出结果。

请注意,因为您想一次完成,所以您必须一次性提供所有必要的信息 - 即使后端不执行创建,IE 您也必须为 createUser 步骤提供足够的信息因为用户已经存在。