Tips for receiving an array input in a GraphQL resolver

My query variables contain an array of strings that I need to use as the ids parameter inside my resolver. Below is the relevant code snippet.

People.resolver.ts

import {
  Resolver, Query, Mutation, Args,
} from '@nestjs/graphql';
import { People } from './People.entity';
import { PeopleService } from './People.service';

@Resolver(() => People)
export class PeopleResolver {
  constructor(private readonly peopleService: PeopleService) { }

  @Mutation(() => String)
  async deletePeople(@Args('ids') ids: string[]) : Promise<String> {
    const result = await this.peopleService.deletePeople(ids);
    return JSON.stringify(result);
  }
}

However, when I try to execute the code, I encounter the following error message,

[Nest] 8247   - 06/22/2020, 6:32:53 PM   [RouterExplorer] Mapped {/run-migrations, POST} route +1ms
(node:8247) UnhandledPromiseRejectionWarning: Error: You need to provide explicit type for PeopleResolver#deletePeople parameter #0 !
    at Object.findType (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/findType.js:17:15)
    at Object.getParamInfo (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/params.js:9:49)
    at /Users/eranga/Documents/Project/node_modules/type-graphql/dist/decorators/Arg.js:9:159
    at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/decorators/args.decorator.js:34:113
    at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:36
    at Array.forEach (<anonymous>)
    at LazyMetadataStorageHost.load (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:22)
    at GraphQLSchemaBuilder.<anonymous> (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:31:57)
    at Generator.next (<anonymous>)
    at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:17:71
(node:8247) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:8247) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I have tried various alternatives like,

@Args('ids', () => string[]) ids: string[]

@Args('ids', () => String[]) ids: String[]

@Args('ids', () => [String]) ids: String[]

@Args('ids', { type: () => String[] }) ids: String[]

Interestingly, changing the mutation to accept a single string input works as expected.

@Mutation(() => String)
async deletePeople(@Args('id') id: string) : Promise<String> {
  const result = await this.peopleService.deletePeople([id]);
  return JSON.stringify(result);
}

Does anyone understand why this problem occurs?

Answer №1

If you define the input type argument like this, it will work:

@Args({ name: 'ids', type: () => [String] }) ids: String[]

Here is an example of how the mutation resolver is structured:

@UseGuards(GraphqlAuthGuard)
@Mutation(() => String)
async deletePeople(@Args({ name: 'ids', type: () => [String] }) ids: String[]) : Promise<String> {
  const result = await this.peopleService.deletePeople(ids);
  return JSON.stringify(result);
}

Credit goes to @vinujan.s

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reasoning behind TypeScript allowing the reading of an undefined variable within a closure?

While exploring, I came across this detail that seems undocumented. Here's some legitimate TypeScript code that results in undefined being output: let x: number; const f= () => { const y= x; console.log(y); } f(); Playground Within the fu ...

Ways to dynamically configure Angular form data

Below is an Angular form group that I need help with. My goal is to initialize the form and if there is no data coming into the Input() data property, then set the form values as empty strings '' for user input. However, if there is indeed form d ...

The key is not applicable for indexing the type as expected

Here is the TS code I am working with: type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" }; type FruitTaste<TFruit extends Fruit> = TFruit["kind"] extends "apple" ? "good" : TFruit["color"] extends "green" ? "good" : ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

Tips for Using JSON as Input in PUT and POST Requests in Android REST Service

I am looking to utilize a REST web service in my Android application, using both GET and POST methods with JSON format. However, I am unsure of how to properly consume the data from the server. Can you please provide guidance on how to effectively retrie ...

Different results are being obtained when destructuring props in a component

Just diving into the world of React and trying to grasp destructuring. I've been doing some reading on it, but I'm currently stuck. When I try to destructure like this function MList({action}) { // const data = [action];}, I only get 'camera ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

What is the best way to dynamically set an ID in Angular using the pound symbol (#)?

I am currently developing a dynamic Angular 6 application that utilizes dynamic components. My approach involves using @ViewChild('<id>', { read: ViewContainerRef }) <id>; to reference the divs where I intend to populate with dynamic ...

The element of type 'any[]' cannot be assigned to type '[id: string]'

My goal is to develop a versatile API structure, where the properties are functions that return Promises. export type API = { [key: string]: <Params extends any[], Response>(...params: Params) => Promise<Response>, } export interface User ...

Switching from a TypeOrm custom repository to Injectable NestJs providers can be a smooth transition with the

After updating TypeORM to version 0.3.12 and @nestjs/typeorm to version 9.0.1, I followed the recommended approach outlined here. I adjusted all my custom repositories accordingly, but simply moving dependencies into the providers metadata of the createTe ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Can Envs in Bit be linked together?

My React environment is set up at this link: . It is configured with the following dependencies: { /** * standardize your component dependencies. * @see https://bit.dev/docs/react-env/dependencies **/ "policy": { // peer and dev ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Calling GraphQL mutations in ReactPGA

I encountered a 400 Error when making a call from the client to server, and I'm not sure where to start troubleshooting. Oddly enough, when I only include the "id" parameter in the request, everything works fine. However, as soon as I add the additio ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

The Vue Router hooks are not being activated within the component when utilizing Typescript

I've been pondering this issue for quite some time. Despite my extensive search efforts, I am still unable to figure out why the route-hooks are not working in my component: 1. The component is being loaded from RouterView: <router-view class="z1 ...

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

What is the process for obtaining an HTML form, running it through a Python script, and then showcasing it on the screen

I am inquiring about the functionality of html and py script. .... The user enters 3 values for trapezoidal data from the html form: height, length of side 1, and length of side 2, then clicks submit. The entered values are then sent to be calculated using ...