Skip to content
the poor coder

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

Poor Man
Published
Reading time
1 min read
On this page

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:

TypeScript

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

TypeScript

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

TypeScript

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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC