首页 > 解决方案 > 可选参数 - 突变 - TypeGraphQL

问题描述

我想更新一个实体的firstNameand 。lastNameprofile

我希望用户能够同时更新它们或仅更新其中之一。 但是我不知道如何进行突变,以使参数 (firstNamelastName) 之一是可选的。

我当前的代码 如果用户同时输入firstNamelastName

  @Mutation(() => Boolean)
  @UseMiddleware(isAuth)
  async updateProfile(
    @Ctx() {payload}: MyContext,
    @Arg('firstName') firstName: string,
    @Arg('lastName') lastName: string,
  ) {

    try {
      const profile = await Profile.findOne({where: { user: payload!.userId}})
      if (profile) {
        profile.firstName = firstName
        profile.lastName = lastName
        await profile.save();

        return true
      }
      return false
    } catch(err) {
      return false
    }
  }

如果我运行突变(不包括一个参数):

mutation{
  updateProfile(firstName: "test")
}

我得到错误:

"message": "String!" 类型的字段 "updateProfile" 参数 "lastName" 是必需的,但未提供。

我在想一种解决方法可能是在中传递一个默认参数,@Arg但后来我意识到默认参数是静态的,而不是动态的,所以我不能为那个特定的配置文件传递firstNameorlastName

标签: graphqlprisma-graphqltypegraphql

解决方案


要使参数成为可选参数,请将第二个参数传递给@Arg装饰,如下所示:

@Arg('firstName', { nullable: true }) firstName: string,
@Arg('lastName', { nullable: true }) lastName: string,

在 GraphQL 中,参数要么是必需的,要么不是。无法指定“只需要其中一个参数”。如果您需要这种验证逻辑,则需要在解析器中自己实现它。


推荐阅读