Created
February 12, 2025 12:02
-
-
Save keizie/7cc6d43d4751c0042ae2fb3544f0bb02 to your computer and use it in GitHub Desktop.
nest.js service from prisma $extends (type 1)
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 } from '@prisma/client' | |
import { faker } from '@faker-js/faker' // 샘플 문자열 생성 용도 | |
@Injectable() | |
export class DatabaseService | |
extends getExtendedClient() | |
implements OnModuleInit, OnModuleDestroy | |
{ | |
async onModuleInit() { | |
await this.$connect() | |
} | |
async onModuleDestroy() { | |
await this.$disconnect() | |
} | |
} | |
// https://github.com/prisma/prisma/issues/18628#issuecomment-1584985619 | |
function getExtendedClient() { | |
const extendedClient = () => { | |
// extends 안에서 client를 추출할 다른 방법을 못 찾아서 직접 client 변수를 선언 | |
const client = new PrismaClient().$extends({ | |
name: 'webinarAfterCreate', | |
query: { | |
webinar: { | |
async create({ args, query }) { | |
console.log('webinarAfterCreate', args) | |
const result = await query(args) | |
console.log(result) | |
// afterCreate logic | |
console.log( | |
await client.topBanner.create({ | |
data: { | |
title: faker.commerce.product(), | |
url: | |
// 이미 create가 끝난 webinar의 값을 참조할 수 있음 | |
'https://papago.naver.com/' + | |
result.title, | |
}, | |
}), | |
) | |
return result | |
}, | |
}, | |
}, | |
}) | |
return client | |
} | |
return class { | |
constructor() { | |
return extendedClient() | |
} | |
} as new () => ReturnType<typeof extendedClient> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment