What is the process for extracting TypeScript types from GraphQL query and mutation fields in order to get args?

I am experiencing difficulties with utilizing TypeScript and GraphQL. I am struggling to ensure that everything is properly typed.
How can I achieve typed args and parent properties in Root query and mutation fields?

For instance: Server:

export interface IContext {
  res: Response;
  req: Request;
  prisma: PrismaClient;
}

const schema = new GraphQLSchema({
    query,
});

  const server = new ApolloServer({
    schema,
    context: ({ req, res }: { req: Request; res: Response }) => ({
      req,
      res,
      prisma,
    }),
  });

Root Query:

const query = new GraphQLObjectType<any, IContext>({
  name: 'QueryType',
  fields: {
    notifications: {
      type: new GraphQLList(NotificationType),
      args: { filter: { type: FindManyNotificationArgs } },
      resolve: async (parent, args, { req, prisma }) => {
        // parent is any 
        // args is [argName: string]: any;
        //req and prisma are typed only due to IContext interface at root query
        try {
          isAuth(req);
          return await prisma.notification.findMany({ ...args.filter });
        } catch (error) {
          throw new Error(error);
        }
      },
    },
    messages: {
      type: new GraphQLList(MessageType),
      args: { filter: { type: FindManyMessageArgs } },
      resolve: async (parent, args, { req, prisma }) => {
        // parent is any 
        // args is [argName: string]: any;
        //req and prisma are typed only due to IContext interface at root query
        try {
          isAuth(req);
          return await prisma.message.findMany({ ...args.filter });
        } catch (error) {
          throw new Error(error);
        }
      },
    },
  },
});

Message types:

export const MessageType = new GraphQLObjectType<Message, IContext>({
  name: 'Message',
  fields: () => ({
    id: { type: GraphQLID },
    ...
    content: { type: GraphQLString },
    hasAttachment: { type: GraphQLBoolean },
    created: { type: GraphQLDateTime },
    updated: { type: GraphQLDateTime },
    expired: { type: GraphQLDateTime },
  }),
});

export const FindManyMessageArgs = new GraphQLInputObjectType({
  name: 'FindManyMessageArgs',
  fields: () => ({
    where: { type: MessageWhereInput },
    orderBy: { type: MessageOrderByInput },
    take: { type: GraphQLInt },
    skip: { type: GraphQLInt },
  }),
});

export const MessageWhereInput: GraphQLInputObjectType =
  new GraphQLInputObjectType({
    name: 'MessageWhereInput',
    fields: () => ({
      id: { type: GraphQLID },
      personId: { type: GraphQLInt },
      person: { type: PersonWhereInput },
      personDocumentStatusId: { type: GraphQLInt },
      personDocumentStatus: { type: PersonDocumentStatusWhereInput },
      content: { type: StringFilter },
      created: { type: GraphQLDateTime },
      updated: { type: GraphQLDateTime },
      expired: { type: GraphQLDateTime },
      AND: { type: MessageWhereInput },
      OR: { type: GraphQLList(MessageWhereInput) },
      NOT: { type: MessageWhereInput },
    }),
  });

How do I correctly define TypeScript types to ensure full typing in rootquery and mutationquery from my defined types

like from

type: new GraphQLList(NotificationType), (This should be parent in resolve function)
args: { filter: { type: FindManyNotificationArgs } },) (This should be args in resolve function)

Thank you!

Answer №1

It has been discovered that arguments cannot be automatically typed for security reasons, since arguments have the potential to be anything.

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

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

Issue encountered when attempting to run "ng test" in Angular (TypeScript) | Karma/Jasmine reports an AssertionError stating that Compilation cannot be undefined

My development setup includes Angular with TypeScript. Angular version: 15.1.0 Node version: 19.7.0 npm version: 9.5.1 However, I encountered an issue while running ng test: The error message displayed was as follows: ⠙ Generating browser application ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...

What is the best way to retrieve all designs from CouchDB?

I have been working on my application using a combination of CouchDB and Angular technologies. To retrieve all documents, I have implemented the following function: getCommsHistory() { let defer = this.$q.defer(); this.localCommsHistoryDB ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

Exploring Angular 4.3's HTTP Interceptor Retry功能

As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. Howe ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

Create a TypeScript view component that encapsulates an HTMLElement for seamless integration with TweenMax

Looking to develop my own basic view component class that encompasses an HTMLElement or JQuery element, I want to be able to do something similar to this: var newComponent:CustomComponent = new CustomComponent($('#someDiv')); TweenMax.to(newCom ...

Error encountered while transforming object due to index type mismatch

I am attempting to change the values of an object, which consist of arrays with numbers as keys, to their respective array lengths. However, I received a type error that says 'Element implicity has any type because a string element cannot be used to ...

The ViewChild from NgbModalModule in @ng-bootstrap/ng-bootstrap for Angular 6 is causing the modal to return as

I have successfully integrated ng bootstrap into my project, specifically utilizing the modal module to display a contact form. The form includes input fields for email and message, as well as a submit button. You can find the ngbootstrap module I am using ...

Merge two observables together to create a single observable that emits values from both sources. Only one observable will emit values

I am looking to combine two observables of type T[] obtained from httpservice. I have tried using forkJoin and zip, but they both return an Observable of type [T[], T[]]. However, I want to receive an object of type T[] as shown in the following code snip ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

Assigning initial value to a BehaviorSubject in an Angular application

I'm still getting the hang of Rxjs. How do I go about initializing the first value of a BehaviorSubject with data from a custom select box model? Here's what the model looks like: private mainRangeDate: any = {beginDate: {year: 2018, mon ...

Directing non-www to www in Next.js has never been easier

Based on the information I've gathered, it seems that using www is more effective than not using it. I am interested in redirecting all non-www requests to www. I am considering adding this functionality either in the next.config.js file or, if that& ...

Achieving CommonJS imports compilation with Typescript

In my TS file, I've included a 3rd party package using import XXX { YYY, ABC, 123 } from 'XXX'; While it compiles to CommonJS without any issues, I'd prefer to have it compiled to an ESModule instead. I tried changing the target and mo ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

The parameters 'event' and 'payload' do not match in type

Upon running the build command, I encountered a type error that states: Type error: Type '(event: React.FormEvent) => void' is not assignable to type 'FormSubmitHandler'. Types of parameters 'event' and 'payload&apos ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Angular2: Unable to locate the 'environment' namespace

After configuring my tsconfig.json, I can now use short import paths in my code for brevity. This allows me to do things like import { FooService } from 'core' instead of the longer import { FooService } from '../../../core/services/foo/foo. ...

How can one effectively outline the structure of a document within firestore?

Currently, I am enclosing my calls to Firebase within a function so that I can specify the return type within the function. This allows me to define the type of data being retrieved from a document. However, TypeScript complains if you do not convert the F ...