Skip to content

Instantly share code, notes, and snippets.

@keizie
Created February 13, 2025 12:46
Show Gist options
  • Save keizie/eae32308f121fedd7db8ed9a6f836d84 to your computer and use it in GitHub Desktop.
Save keizie/eae32308f121fedd7db8ed9a6f836d84 to your computer and use it in GitHub Desktop.
nest.js service from prisma $extends (type 3)
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);
}
}
@keizie
Copy link
Author

keizie commented Feb 13, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment