What is the process for integrating GraphQL resolvers in Typescript using Graphql-codegen?

With the goal of learning Apollo Server, I decided to implement the schema outlined here. The CodeGen produced what seemed to be logical type definitions for books and libraries.

export type Book = {
  __typename?: 'Book';
  author: Author;
  title: Scalars['String'];
};

export type Library = {
  __typename?: 'Library';
  books?: Maybe<Array<Book>>;
  branch: Scalars['String'];
};

The issue arose when the example code (Javascript) provided data for books and libraries as:

  {
    branch: "riverside",
  }

and

  {
    title: "The Awakening",
    author: "Kate Chopin",
    branch: "riverside",
  }

In the Javascript, each child had the ID of its parent, but in the GraphQL schema, each parent had an array of its children. This led to confusion when trying to apply the Resolvers type, resulting in compiler errors questioning the absence of a child array.

It seems that Apollo and GraphQL CodeGen are robust tools, therefore it puzzled me why such a fundamental concept was overlooked. What am I overlooking here?

(On a side note, I stumbled upon this question which appears to touch on the same dilemma.)

Answer №1

An unexpected source provided me with the solution - a YouTube video I stumbled upon, where the answer was casually mentioned towards the end (starting at 5:38).

Within the codegen.yml, it is essential to specify the types of the default objects that the resolvers will return to the generator. In my case, I defined the types in Typescript as follows:

export type LibraryModel = typeof libraries[number];
export type BookModel = typeof books[number];

Subsequently, I instructed the generator in the codegen.yml to utilize these types:

     config:
       mappers:
         Library: ../service/libraries#LibraryModel
         Book: ../service/libraries#BookModel

(Please note: The path specified here is relative to the location of the generated file.)

This approach proves beneficial for me as I plan to implement an ORM that auto-generates types from the database, aligning well with the existing scalar names and ultimately reducing manual effort.

However, this method comes with its drawbacks as it compromises some degree of type-safety. If a field is not handled by either the default resolver or a specific one, it may lead to runtime errors that go unnoticed by the type system. Not ideal!

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

Storing JSON data retrieved from an API into a class property using the fetch function: a step-by-step guide

I am faced with the challenge of communicating with a localhost API that I have created in my React application class. This API is responsible for returning a list of JSON data, and my goal is to store this data in a property. Having limited knowledge abo ...

Having trouble with your React/TypeScript/Redux/Thunk action not dispatching and the state remaining unchanged?

Currently, I am facing an issue while attempting to send a GET request to an API using React-Redux & TypeScript. The goal is to dispatch an action upon clicking a button (onClick event), make the request, update the state via the reducer, and finally log t ...

Issue with data-* attributes in MaterialUI React component causing TypeScript error

I am encountering an issue while attempting to assign a data-testid attribute to a Material-UI Select component. The Typescript error I am facing is as follows: Type '{ "data-testid": string; }' is not compatible with type 'HTMLAttributes&a ...

Tips for utilizing generated *.d.ts files

I have been utilizing a Visual Studio 2017 extension called TypeScript Definition Generator to automatically create TypeScript interfaces for my MVC-ViewModels. Despite trying various similar tools, they all seem to result in the same output (*.cs.d.ts-Fil ...

The addition of types/cors in Express Typescript causes my POSTMAN request to hang indefinitely

I am experiencing an issue with my React web app and Express TypeScript backend. Previously, my POST request was functioning well, but now it seems to hang indefinitely on Postman without returning any errors. issueController.ts import { RequestHandler } ...

How can we achieve a seamless fade transition effect between images in Ionic 2?

My search for Ionic 2 animations led me to some options, but none of them quite fit what I was looking for. I have a specific animation in mind - a "fade" effect between images. For example, I have a set of 5 images and I want each image to fade into the ...

Struggling with TypeScript errors due to React.HTMLProps for HTMLAnchorElement

When trying to extend a React component with React.HTMLProps without explicitly defining onClick in the attribute list, ESLint complains when passing onClick as an attribute while using the component. Here's an example of the code: The React componen ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Module '@tanstack/react-table' cannot be located even though it has been successfully installed

Currently, I am tackling a TypeScript React project and encountering an issue while attempting to import ColumnDef from @tanstack/react-table in my columns.tsx file. import { ColumnDef } from "@tanstack/react-table"; export type Payment = { id ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

Leveraging the sofa API within a minimalist Express server configuration

Hey there. I've set up a very basic express graphql server. I'm looking to utilize sofa-api to add REST functionality. I'm facing two issues: When accessing /api/hello, it should display "Hello World!", but currently it shows as null. ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

Problem with Grouping of Columns in Material-UI

Having some trouble with column grouping in MUI data grid pro. I am using typescript and trying to implement column grouping, but encountering issues with the module GridColumnGroupingModel, which is used as the type definition for columnGroupingModel. Fol ...

Determining the return type based on an optional generic type in TypeScript

I have created a function that generates an object (map) [key] : value from an array. My goal is to make the value method optional, and if not provided, simply return the item as it is. Here is the code I have written: export default class ArrayUtil ...

The mutation involving the variable "$_v0_data" containing a list of strings has received an invalid value in Graphql using Node.js

I have a basic mutation that is functioning properly type Mutation { addJob( url: String! description: String! position: String! company: String! date: DateTime! tags: [String!]! ): Job } Resolv ...

Encountering issues when passing a string as query parameters

How can I successfully pass a string value along with navigation from one component to another using query parameters? Component1: stringData = "Hello"; this.router.navigate(['component2'], { queryParams: stringData }); Component2: ...

Using TypeScript with AWS Lambda: To package imports or not to package? Alternatively: Error in Runtime.ImportModule: Module '@aws-sdk/...' not found

I have been working with the code in my lambda.ts file, attempting to execute it on an AWS Lambda: import 'aws-sdk' import { /* bunch of stuff... */ } from "@aws-sdk/client-cloudwatch-logs"; import {Context, APIGatewayProxyResult} from ...

Top method for allowing non-component functions to update Redux state without the need to pass store.dispatch() as a parameter

As I work on my first ReactJS/redux project, I find myself in need of some assistance. I've developed a generic apiFetch<T>(method, params) : Promise<T> function located in api/apiClient.ts. (Although not a React component, it is indirect ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

How can one ensure that the element declared in the "let" clause is displayed in an HTML Angular template?

I am working on a component that can render a mat-table. Each cell can have a specified value, or if it is present, the component calls an ngTemplateOutlet and passes it a rendering function obtained from the calling object. export interface ColumnConfig { ...