[英]TypeGraphql and Prisma 2 type conflicts
我在帶有 PostgreSQL 數據庫的 Apollo Express 服務器上使用 TypeGraphql 和 Prisma 2。
我使用 Prisma 來檢查我的數據庫,然后從schema.prisma
生成 TypeScript 類型。
我也有使用 TypeGraphQL 制作的@ObjectType
模型類。
我的問題是我似乎遇到了 TypeGraphQL 類和 Prisma 生成的類型之間的類型沖突。 例如,我有一個 TypeGraphQL Course
類,看起來像這樣
@ObjectType()
export class Course {
@Field(() => Int)
id: number;
@Field()
title: string;
.......
@Field(() => User)
creator: User;
}
Prisma 生成一個Course
類型,如下所示:
/**
* Model Course
*/
export type Course = {
id: number
title: string
.......
creator_id: number
}
因此,在我的自定義解析器中,當我嘗試創建Course
,我說突變返回一種類型的Course
。 (我有一個使用此服務的控制器,但該服務是問題所在)
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;
};
但Course
是來自我TypeGraphQL類類型是不同的Course
由Prisma的生成的類型,但它們命名相同的,所以打字稿那種認為它們是相同的,但給錯說,創作者在缺少型Course
,但需要在類型Course
。 不確定解決此問題的最佳方法是什么。
有沒有辦法將我的 TypeGraphQL 類和我的 Prisma 類型拼接在一起或以其他方式進行處理?
導入類型時,您可以使用as
關鍵字(進行類型斷言)並重命名其中一種類型。 例如,您可以將Course
從 Prisma 重命名為PrismaCourse
、 DBCourse
或CourseModel
或您喜歡的任何其他名稱。 這是用於此的語法:
import { Course as DBCourse } from '@prisma/client'
然后,在您的解析器中,您可以擁有以下代碼:
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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.