【问题标题】:Nexus field resolver parent type is not nullableNexus 字段解析器父类型不可为空
【发布时间】:2021-01-13 12:21:38
【问题描述】:

任何人都可以使用他们想要的任何字段查询用户,但是出于某种原因 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',
      nullable: true,
      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
      },
    })
  },
})

【问题讨论】:

    标签: prisma nexus-prisma


    【解决方案1】:

    这很正常,您的查询解析器可能正在使用 ORM 或 DB 客户端来检索所有用户数据 (colmun),包括您不需要/不想要的这些数据。这就是为什么您的parent“充满了不需要的数据”。但这并不重要,重要的是您要公开哪个字段(在您的情况下为 idnicknameq_is_public)。您的 API 之外的任何人都无法访问未公开的数据。

    换句话说,parent 参数中的用户数据是由 DB/ORM 客户端直接提供的。而且您的 GraphQL 服务器不会全部公开(取决于您的 t.model)。

    您可以通过仅从您的数据库中请求 idnicknameq_idq_is_public 列来优化您的 API .但是,如果将来您需要公开更多字段,则必须更新数据库查询以检索更多列。

    【讨论】:

      【解决方案2】:

      我认为最好的选择是使用 nexus 生成的类型将类型重新定义为 Partial

      resolve: (parent: DeepPartial<NexusTypesGen.NexusGenFieldTypes['User']>) => {}
      

      【讨论】:

        猜你喜欢
        • 2020-05-23
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        • 2019-07-20
        • 2017-04-19
        • 2022-06-17
        • 2021-08-23
        • 1970-01-01
        相关资源
        最近更新 更多