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!