Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional argument - Mutation - TypeGraphQL

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

like image 891
Magofoco Avatar asked Dec 23 '22 17:12

Magofoco


1 Answers

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.

like image 171
Daniel Rearden Avatar answered Feb 03 '23 19:02

Daniel Rearden