Prisma Self Relation with GraphQL in NestJS

Viewed 557

I'm having issues with using prisma + graphQL + nestjs. It keeps on telling me that it is unable to determine a graphQL input type "Error: Cannot determine a GraphQL input type ("Org") for the "parent". Make sure your class is decorated with an appropriate decorator."

This is my prisma schema,

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
}

This is the dto for creation

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;
}

Entity

import { ObjectType } from '@nestjs/graphql';
import { Org as PrismaOrg } from '@prisma/client';

@ObjectType()
export class Org implements PrismaOrg {
  parentId: string;
  id: string;
  name: string;
}

part of the resolver

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);
  }

Part of the servicer

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,
    });
  }

How do we deal with self relations in graphQL? Do we need to just use basic strings in the graphQL input but then do th4e self relation within prisma? Or is there a better way?

Thank you!

1 Answers

I had the same kind of issues with Nest and Prisma. I have resolved it this way.

@ObjectType()
export class Type {
    @Field(() => [Type])
    subs: Type[];
}
Related