如何解决Nexus字段解析器父类型不可为空
任何人都可以使用所需的任何字段来查询用户,但是由于某种原因q_id字段解析器的父类型包括所有字段。如何修复父类型并使每个字段为空?
我只想在q_is_public时加载q_id(它可以工作,但是我要记住,parant字段可以是未定义的)。
import { extendType,inputObjectType,objectType,arg } from '@nexus/schema'
export const User = objectType({
name: 'User',definition(t) {
t.model.id()
t.model.nickname()
t.model.q_is_public()
t.field('q_id',{
type: 'Int',nullable: true,resolve: (parent) => {
/*
parent type is:
{
id: number;
nickname: string;
q_is_public: boolean;
}
parent type actual:
{
id?: number;
nickname?: string;
q_is_public?: boolean;
q_id?: boolean;
... and so on,what user requested
}
*/
return parent?.q_is_public ? parent?.q_id : null
},})
},})
const FindOneUserInput = inputObjectType({
name: 'FindOneUserInput',definition(t) {
t.int('id',{ required: true })
},})
export const FindOneUser = extendType({
type: 'Query',definition(t) {
t.field('findOneUser',{
type: 'User',args: { where: arg({ type: FindOneUserInput,required: true }) },resolve: async (_parent,{ where },{ db },_info) => {
// here will be used pal.select instead all fields load,to load only selected fields
const res = await db.user.findOne({
where,})
return res
},})
解决方法
很正常,您的查询解析器可能正在使用ORM或DB客户端来检索所有用户数据(权限),包括不需要/想要的用户数据。这就是为什么您的parent
“充满了不需要的数据”的原因。但这并不重要,重要的是要公开哪个字段(在您的情况下为 id ,昵称和 q_is_public )。您的API的“外部”没有人可以访问未公开的数据。
换句话说,您在parent
参数中拥有的用户数据直接由您的DB / ORM客户端提供。而且您的GraphQL服务器不会全部公开(取决于您的t.model
)。
您可以通过仅向数据库请求 id ,昵称, q_id 和 q_is_public 来优化API。 。但是,如果将来需要公开更多字段,则必须更新数据库查询以检索更多列。
,我认为最好的选择是使用nexus生成的类型将类型重新定义为Partial
resolve: (parent: DeepPartial<NexusTypesGen.NexusGenFieldTypes['User']>) => {}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。