Created
November 21, 2022 03:45
-
-
Save chhornponleu/56258f7fe108144ffc162175b5423e88 to your computer and use it in GitHub Desktop.
nestjs: prisma service with read instance
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 } 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(); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ref: prisma/prisma#172 (comment)