You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphQL如何正确解析返回类型为Boolean的收件人匹配查询

问题根因
  • 服务层getRecipientByContact返回的是未执行的异步函数定义,不是实际查询结果,也没有返回符合要求的布尔值
  • 数据库查询层selectByContact参数定义和调用逻辑不匹配,且仅拼接了查询条件没有执行查询,也未做存在性判断
  • 全链路最终没有返回合法布尔值,触发了GraphQL非空字段Boolean!的空值报错

修正代码

1. 数据库查询层

selectByContact({ email, phone }) { // 调整参数为接收对象,和调用逻辑匹配
  const query = this.tx(tableName)
  if (email) query.where(columns.email, email)
  if (phone) query.where(columns.phone, phone)
  return query.first() // 仅取第一条匹配结果,减少不必要的数据查询
}

2. 服务层

async getRecipientByContact({ email, phone }) { // 改为async函数直接处理异步逻辑
  const { UserInputError } = this.errors;

  if (isEmpty(email) && isEmpty(phone))
    throw new UserInputError(`Specify an email or phone number`);

  // 执行查询后直接转布尔值返回
  const existContact = await this.recipient.selectByContact({ email, phone });
  return !!existContact;
}

3. 解析器保持原有逻辑即可

Query: {
    recipientByContact(_, args, user) {
      return recipientService(user).getRecipientByContact(args);
    },
}

逻辑校验
  • 仅传入手机号:仅拼接手机号查询条件,匹配到记录返回true,否则返回false
  • 仅传入邮箱:仅拼接邮箱查询条件,匹配到记录返回true,否则返回false
  • 同时传入两者:两个查询条件同时生效,只有两者完全匹配的记录才会命中,符合需求

内容的提问来源于stack exchange,提问作者Jakub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 23:06:03