Created
February 13, 2025 12:46
-
-
Save keizie/eae32308f121fedd7db8ed9a6f836d84 to your computer and use it in GitHub Desktop.
nest.js service from prisma $extends (type 3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, OnModuleDestroy, OnModuleInit, Type } from '@nestjs/common'; | |
import { PrismaClient, Prisma } from '@prisma/client'; | |
const existsExtension = Prisma.defineExtension({ | |
name: 'exists-extension', | |
model: { | |
$allModels: { | |
async exists<T>(this: T, where: Prisma.Args<T, 'findFirst'>['where']): Promise<boolean> { | |
const context = Prisma.getExtensionContext(this); | |
const result = await (context as any).findFirst({ where }); | |
return result !== null; | |
} | |
} | |
} | |
}); | |
@Injectable() | |
export class PrismaProvider extends PrismaClient implements OnModuleInit, OnModuleDestroy { | |
private static initialized = false; | |
constructor() { | |
super(); | |
} | |
onModuleInit() { | |
if (!PrismaProvider.initialized) { | |
PrismaProvider.initialized = true; | |
return this.$connect(); | |
} | |
} | |
onModuleDestroy() { | |
if (PrismaProvider.initialized) { | |
return this.$disconnect(); | |
} | |
} | |
withExtensions() { | |
return this.$extends(existsExtension); | |
} | |
} | |
const ExtendedPrismaClient = class { | |
constructor(provider: PrismaProvider) { | |
return provider.withExtensions(); | |
} | |
} as Type<ReturnType<PrismaProvider['withExtensions']>>; | |
@Injectable() | |
export class PrismaService extends ExtendedPrismaClient { | |
constructor(provider: PrismaProvider) { | |
super(provider); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
prisma/prisma#18628 (comment)