Skip to content

Instantly share code, notes, and snippets.

@chhornponleu
Created November 21, 2022 03:45
Show Gist options
  • Select an option

  • Save chhornponleu/56258f7fe108144ffc162175b5423e88 to your computer and use it in GitHub Desktop.

Select an option

Save chhornponleu/56258f7fe108144ffc162175b5423e88 to your computer and use it in GitHub Desktop.
nestjs: prisma service with read instance
import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
import { PrismaClient, Session, User } from "@prisma/client";
import * as _ from "lodash";
import * as minimatch from "minimatch";
import { AppConfigService } from "../app-config/app-config.service";
@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
private readonlyInstance: PrismaClient;
constructor(private appConfigService: AppConfigService) {
this.readonlyInstance = new PrismaClient({
datasources: { postgresql: { url: this.appConfigService.db.readUrl } },
});
}
async onModuleInit() {
await this.$connect();
await this.readonlyInstance.$connect();
this.$use(async (params, next) => {
if (minimatch(params.action, "find*")) {
const res = await this.readonlyInstance[_.camelCase(params.model)][
params.action
](params.args);
return res;
}
const result = await next(params);
return result;
});
}
async onModuleDestroy() {
await this.$disconnect();
await this.readonlyInstance.$disconnect();
}
}
@chhornponleu
Copy link
Author

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