how to give args type in nestjs graphql for array of input

How to Give Args Type in NestJS GraphQL for Array of Input

If you're using NestJS with GraphQL, you may come across a situation where you need to pass an array of input as an argument. In this case, you need to define the input type and then use it as an argument in your resolver function.

Step 1: Define the Input Type

You need to create a new class with the required properties of your input type. For example, let's say you want to pass an array of User objects as an argument. Your input class will look something like this:


    @InputType()
    class UserInput {
        @Field()
        name: string;
        
        @Field()
        email: string;
    }
    

Here, @InputType() decorator is used to define the class as an input type. The @Field() decorator is used to define each property of the input type.

Step 2: Use the Input Type as an Argument

Now that you have defined your input type, you can use it as an argument in your resolver function. Here's how:


    @Mutation(() => Boolean)
    async createUser(@Args('users', { type: () => [UserInput] }) users: UserInput[]): Promise {
        // Your resolver function code goes here
        return true;
    }
    

Here, the @Args() decorator is used to define the argument name ('users') and its type. The 'type' property is set to () => [UserInput], which means an array of UserInput objects.

Alternative Approach

Another approach to defining the argument type for an array of input is to use the @InputType() decorator directly on the resolver function argument. Here's how:


    @Mutation(() => Boolean)
    async createUser(@Args({ name: 'users', type: () => [UserInput] }) users: UserInput[]): Promise {
        // Your resolver function code goes here
        return true;
    }
    

Here, the @Args() decorator is used to define the argument name ('users') and its type. The 'type' property is set to () => [UserInput], which means an array of UserInput objects.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe