TypeScript - ความสัมพันธ์ตัวเองของ Prisma กับ GraphQL ใน NestJS
ฉันกำลังมีปัญหาในการใช้ Prisma + GraphQL + NestJS มันยังคงบอกฉันว่าไม่สามารถระบุประเภท input ของ GraphQL ได้ "Error: Cannot determine a GraphQL input type ("Org") for the "parent". ตรวจสอบให้แน่ใจว่าคลาสของคุณถูกตกแต่งด้วย decorator ที่เหมาะสม."
นี่คือสกีมาของ Prisma ของฉัน
model Org {
id String @id @default(uuid())
name String
parentId String? //an org can have a single parent org
parent Org? @relation("ParentChildren", fields: [parentId], references: [id])
children Org[] @relation("ParentChildren") // This is a self relation
}
นี่คือ dto สำหรับการสร้าง
import { Field, InputType } from '@nestjs/graphql';
import { Prisma } from '@prisma/client';
import { Org } from '../entities/org.entity';
@InputType()
export class OrgCreateInput implements Prisma.OrgCreateInput {
name: string;
@Field((type) => Org)
parent?: Prisma.OrgCreateNestedOneWithoutChildrenInput;
@Field((type) => Org)
children?: Prisma.OrgCreateNestedManyWithoutParentInput;
id?: string;
}
หน่วยงาน
import { ObjectType } from '@nestjs/graphql';
import { Org as PrismaOrg } from '@prisma/client';
@ObjectType()
export class Org implements PrismaOrg {
parentId: string;
id: string;
name: string;
}
ส่วนของตัวแก้ไข
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { OrgService } from './org.service';
import { Org } from './entities/org.entity';
import { OrgCreateInput } from './dto/create-org.input';
import { UpdateOrgInput } from './dto/update-org.input';
@Resolver(() => Org)
export class OrgResolver {
constructor(private readonly orgService: OrgService) {}
// create a org
@Mutation(() => Org, { name: 'createOrg' })
async createOrg(@Args('orgCreateInput') orgCreateInput: OrgCreateInput) {
return this.orgService.create(orgCreateInput);
}
ส่วนหนึ่งของผู้ให้บริการ
import { Injectable } from '@nestjs/common';
import { Prisma, Org } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class OrgService {
constructor(private prisma: PrismaService) {}
async create(data: Prisma.OrgCreateInput): Promise<Org> {
return this.prisma.org.create({
data,
});
}
เราจะจัดการกับความสัมพันธ์ตัวเองใน GraphQL อย่างไร? เราจำเป็นต้องใช้เพียงสตริงพื้นฐานในอินพุตของ GraphQL แต่จากนั้นทำความสัมพันธ์ตัวเองใน Prisma หรือไม่? หรือมีวิธีที่ดีกว่านี้?
ขอบคุณ!
คำตอบ #1
ฉันเคยมีปัญหาแบบเดียวกันกับ Nest และ Prisma ฉันได้แก้ไขมันด้วยวิธีนี้
@ObjectType()
export class Type {
@Field(() => [Type])
subs: Type[];
}
