6

I want to update the firstName and lastName of a profile entity.

I would like the user to be able to update both of them or just one of them. However I do not know how to make the mutation such that one of the argument (firstName and lastName) is optional.

My Current code It works if the user inputs both firstName and lastName

  @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
    }
  }

If I run the mutation (excluding one argument):

mutation{
  updateProfile(firstName: "test")
}

I get the error:

"message": "Field "updateProfile" argument "lastName" of type "String!" is required, but it was not provided.

I was thinking that a workaround could be passing a default argument in the @Arg but then I realised that the default argument is static, not dynamic so I cannot pass the firstName or lastName for that specific profile

Magofoco
  • 5,098
  • 6
  • 35
  • 77

1 Answers1

13

To make an argument optional, pass a second parameter to the @Arg decorate like this:

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

In GraphQL, arguments are either required or they are not. There is no way to specify "only one of these arguments is required". If you need that kind of validation logic, you'll need to implement it yourself inside the resolver.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thanks. Do you suggest to create a mutation for each argument? One to update the `firstName` and one to update the `lastName`? Can this be a solution? My fear is that I will have too many mutations if I follow this path – Magofoco Aug 08 '20 at 12:11
  • 1
    It really depends on your use case. As a rule of thumb, though, it's better to have more granular queries and mutations so that their intent is more clearly communicated to anyone consuming them. – Daniel Rearden Aug 08 '20 at 13:28