【问题标题】:Can we return a string or object in grapqhl while resolving?我们可以在解析时在graphql中返回一个字符串或对象吗?
【发布时间】:2021-06-17 18:33:49
【问题描述】:

我想检查用户是否存在于数据库中...如果用户存在于数据库中然后发送

type user{
  name
  email
  password
  username
}

或者如果用户在数据库中不存在,则发送一个字符串告诉“用户在数据库中不存在”

like.... 如果我正在写 tyepDefs

type Query{
 show_data(username: String!): #if user exists then# ***user!*** or #if user doesnot exists then# ***String!***

如何制作这种类型的解析器和typeDefs?

【问题讨论】:

标签: node.js graphql apollo-server express-graphql


【解决方案1】:

您可以创建一个新类型以在您的查询中使用:

type UserPayload {
  state: String! # success or other value
  user: User # if state was not success this must be null
}

然后通过您的查询直接使用该类型,如下所示:

type Query{
 show_data(username: String!):UserPayload 
}

【讨论】:

  • 展示如何使用以下查询在操场上玩耍...
  • 您可以正常使用您的查询... show_data(username:"Username"){ state user } state 是您要的字符串变量。 user 可以为空,它返回 null 或 User 类型
  • 如果 graphql 是强类型的,那么我认为我不应该关心解析器发送有效结果..如果用户在数据库中不存在,那么它会中断,如果有那么它将发送有效响应
猜你喜欢
  • 2018-09-18
  • 1970-01-01
  • 2018-10-24
  • 2020-05-07
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 2019-11-07
  • 2020-10-04
相关资源
最近更新 更多