首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可选参数-突变- TypeGraphQL

可选参数-突变- TypeGraphQL
EN

Stack Overflow用户
提问于 2020-08-06 23:49:38
回答 1查看 5.3K关注 0票数 6

我想更新firstNamelastNameprofile实体。

我希望用户能够同时更新它们,或者只更新其中一个。然而,,我不知道如何使其中一个参数(firstNamelastName)是可选的。

我的当前代码如果用户输入firstNamelastName,它就能工作

代码语言:javascript
复制
  @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
    }
  }

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

代码语言:javascript
复制
mutation{
  updateProfile(firstName: "test")
}

我知道错误:

"message":"Field "updateProfile“参数”参数"lastName“类型为"String!”是必需的,但没有提供。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-07 00:11:48

若要使参数可选,请向@Arg装饰传递第二个参数,如下所示:

代码语言:javascript
复制
@Arg('firstName', { nullable: true }) firstName: string,
@Arg('lastName', { nullable: true }) lastName: string,

在GraphQL中,参数要么是必需的要么是不需要的。没有办法具体说明“只需要其中一个参数”。如果您需要这种验证逻辑,则需要在解析器中自己实现它。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63293280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档