Can you explain the purpose of the argument provided to @Resolver in type-graphql?

I'm genuinely curious about something. I noticed on the type-graphql documentation website that they include an argument in the @Resolver decorator. You can see this in action on their page here: (look under the "Resolvers" section).

Here is a snippet of the code they provide:

@Resolver(Recipe)
class RecipeResolver {
  constructor(private recipeService: RecipeService) {}

  @Query(() => Recipe)
  async recipe(@Arg("id") id: string) {
    const recipe = await this.recipeService.findById(id);
    if (recipe === undefined) {
      throw new RecipeNotFoundError(id);
    }
    return recipe;
  }

  @Query(() => [Recipe])
  recipes(@Args() { skip, take }: RecipesArgs) {
    return this.recipeService.findAll({ skip, take });
  }

  @Mutation(() => Recipe)
  @Authorized()
  addRecipe(
    @Arg("newRecipeData") newRecipeData: NewRecipeInput,
    @Ctx("user") user: User,
  ): Promise<Recipe> {
    return this.recipeService.addNew({ data: newRecipeData, user });
  }

  @Mutation(() => Boolean)
  @Authorized(Roles.Admin)
  async removeRecipe(@Arg("id") id: string) {
    try {
      await this.recipeService.removeById(id);
      return true;
    } catch {
      return false;
    }
  }
}

Interestingly, my own code functions properly even without passing an argument to @Resolver. While it may not be crucial, I am curious about its purpose. Can anyone shed some light on this for me?

Answer №1

It is utilized within a @FieldResolver function.

The concept of field resolvers in TypeGraphQL mirrors that of queries and mutations. These are set up as methods within the resolver class, but with specific adjustments. Initially, specify which object type fields we are resolving by indicating the type in the @Resolver decorator:

@Resolver(of => Recipe)
class RecipeResolver {
 // includes queries and mutations
}

Subsequently, craft a class method (for example, averageRating) that functions as the field resolver. This method is annotated with the @FieldResolver() decorator. Additionally, apply the @Root decorator to the method parameters to access the recipe object:

@Resolver(of => Recipe)
class RecipeResolver {
  // incorporates queries and mutations

  @FieldResolver()
  averageRating(@Root() recipe: Recipe) {
    const totalRatings = recipe.ratings.reduce((acc, val) => acc + val, 0);
    return recipe.ratings.length ? totalRatings / recipe.ratings.length : null;
  }
}

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

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Generating a JSON list from a Map object utilizing an interface in Angular 9

The map in my project is generated using the countries-map plugin and includes data values. Here is an example of the data provided by the plugin: mapData: CountriesData = { 'ES': { 'value': 416 }, 'GB': { 'value&apos ...

Best practices for configuring a gulpfile.ts

I have configured a gulpfile.ts for my project based on this example from GitHub found here. (I won't be sharing my exact gulpfile.ts as it is similar, just slightly more complex) Every time I run a gulp task, I encounter these 4 errors: [11:53:23] ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

The function does not yield any result

import { Injectable } from '@angular/core'; export class Test { public id: number; public name: string; public fid: number }; export const TESTS2: Test[] = [ {id: 1, name: 'Lion', fid: 1}, {id: 2, name: 'Tiger', fid: 1 ...

Arranging Pipe Methods in RxJS/Observable for Optimal Functionality

In the class Some, there is a method called run that returns an Observable and contains a pipe within itself. Another pipe is used when executing the run method. import { of } from 'rxjs'; import { map, tap, delay } from 'rxjs/operators&ap ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

What is the best way to refresh existing data retrieved by React Query without having to fetch everything again?

My current code structure requires me to refetch all the data after a successful mutation, as the client-side tasks are not updated automatically. Is there a way to update the tasks directly when I create or delete a task? const { data: sessionData } = ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...

What is the reason behind TypeScript classifying the argument type from the function as 'never'?

Presented here is the combined type of two signatures for the filter function and the function itself. type Filter = { (arr: string[], f: (item: string) => boolean): string[] (arr: number[], f: (item: number) => boolean): number[] } let filter: ...

When importing the Ionic Native File, the JavaScript File object cannot be used simultaneously

When attempting to use the javascript file object, I encountered an issue because the ionic native file object already uses the same key File Here is an example: import { File } from '@ionic-native/file'; @Component({ selector: 'page-ho ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

Upon accessing the GraphQL endpoint, Apollo throws an error saying 'Uncaught SyntaxError: Unexpected token <'

Currently, I am immersed in a project that involves utilizing graphql, apollo, and express. Upon visiting the graphql endpoint, an issue arises where a white page is displayed along with an error message in the console Console log error Upon further inves ...

Utilizing ng-class to apply separate conditions to an array of buttons in Angular

I am facing a straightforward issue. I need to create an array of 3 buttons, and upon clicking each button, the background color of the page should change. The catch is that I have to achieve this using pure Angular-TypeScript without the use of JavaScript ...

Is there a way to refresh the ngFor render?

Is there a way to refresh or rerender the ngFor in a component (hello.component.ts)? I'm looking to display images or charts instead of text. Check out this simple example for reference: Stackblitz Here is a potential solution: public show = true; ...