I'm just getting started building code-first GraphQL in NestJS and am struggling with solving the N+1 problem in Prisma. In particular, using FindUnique is where I'm most challenged because the 'n' side of a 1-n relation isn't unique, so I can't figure out how to use the Prisma Fluid API properly.
Here's my Prisma schema:
model Facility {
id String @id @default(uuid())
name String
facilityType FacilityType @relation(fields: [facilityTypeId], references: [id])
facilityTypeId String
}
model FacilityType {
id String @id @default(uuid())
description String @unique
Facility Facility[]
}
Facility Entity
import { ObjectType, Field } from '@nestjs/graphql';
import { FacilityType } from '../../facility-types/entities/facility-type.entity';
@ObjectType()
export class Facility {
@Field({ description: 'Facility UUID' })
id: string;
@Field({ description: 'Facility Name' })
name: string;
@Field((type) => [FacilityType], { description: 'Facility Type Entity' })
facilityType: FacilityType;
@Field({ description: 'Facility Type UUID' })
facilityTypeId: string;
}
FacilityType Entity
import { ObjectType, Field } from '@nestjs/graphql';
import { Facility } from '../../facilities/entities/facility.entity';
@ObjectType()
export class FacilityType {
@Field({ description: 'Facility Type UUID' })
id: string;
@Field({ description: 'Facility Type Description' })
description: string;
@Field((type) => [Facility], {
description: 'Facility Type Facility Entities',
})
facilities: Facility[];
}
This resolver works, but it has the N+1 problem because it runs the @ResolveField "findMany" for each FacilityType.
import { Resolver, Query, ResolveField, Parent } from '@nestjs/graphql';
import { FacilityType } from './entities/facility-type.entity';
import { PrismaService } from 'src/prisma/prisma.service';
import { Facility } from '../facilities/entities/facility.entity';
@Resolver(() => FacilityType)
export class FacilityTypesResolver {
constructor(private readonly prismaService: PrismaService) {}
// Get all facility types
@Query(() => [FacilityType], { name: 'facilityTypes' })
async getFacilityTypes() {
return await this.prismaService.facilityType.findMany();
}
// Resolve facilities
// Has N + 1 Problem
@ResolveField('facilities', (returns) => [Facility])
async resolveFacilities(@Parent() facilityType: FacilityType) {
return await this.prismaService.facility.findMany({
where: { facilityTypeId: facilityType.id },
});
}
}
I would appreciate it if somebody could help me rewrite the ResolveField Prisma code to use the Fluid API, or if that's not what I should be doing, an explanation would be wonderful. Thanks!