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
相关产品推荐
相关产品推荐

