TypeGraphql and Prisma 2 type conflicts

700 views Asked by At

I am using TypeGraphql and Prisma 2 on an Apollo Express server with a PostgreSQL db.

I used Prisma to introspect my DB and then generated the TypeScript types from schema.prisma.

I also have my @ObjectType model classes made with TypeGraphQL.

My issue is that I seem to be running into type conflicts between my TypeGraphQL classes and the generated types from Prisma. For example I have a TypeGraphQL Course class that looks like this

@ObjectType()
export class Course {
  @Field(() => Int)
  id: number;

  @Field()
  title: string;
  .......

  @Field(() => User)
  creator: User;
}

and Prisma generates a Course type that looks like this:

/**
 * Model Course
 */

export type Course = {
  id: number
  title: string
  .......
  creator_id: number
}

So in my custom resolvers, when I try to create a Course, I say that the mutation returns a type of Course. (I have a controller using this service but the service is where the issue is)

export const createCourseService = async (
  prisma: PrismaClient,
  createCourseInput: CreateCourseInput,
  userId: number
): Promise<Course> => {
  let err, newCourse, foundUser;
  const { course, user } = prisma;

  .....

  [err, newCourse] = await to(
    course.create({
      data: {
        ...createCourseInput,
        creator: {
          connect: { id: userId },
        },
      },
    })
  );
  return newCourse;
};

But the Course type that comes from my TypeGraphQL class is different from the Course type generated by Prisma but they're named the same so TypeScript sort of thinks they're the same but gives and error saying that creator is missing in type Course but required in type Course. Not really sure what the best way to resolve this is.

Is there some way to stitch my TypeGraphQL classes and my Prisma types together or go about it some other way?

1

There are 1 answers

0
nburk On

When importing the types, you can use as keyword (doing a type assertion) and rename one of the types. You could e.g. rename the Course from Prisma to PrismaCourse, DBCourse or CourseModel or anything else you prefer. Here's the syntax to use for that:

import { Course as DBCourse } from '@prisma/client'

Then, in your resolver you can have the following code:

export const createCourseService = async (
  prisma: PrismaClient,
  createCourseInput: CreateCourseInput,
  userId: number
): Promise<DBCourse> => {
  let err, newCourse, foundUser;
  const { course, user } = prisma;

  .....

  [err, newCourse] = await to(
    course.create({
      data: {
        ...createCourseInput,
        creator: {
          connect: { id: userId },
        },
      },
    })
  );
  return newCourse;
};