Created
May 14, 2022 00:33
-
-
Save sunnyy02/67982508bbe89cbfeef642d07d5e068b to your computer and use it in GitHub Desktop.
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
| // Firstly, we need a schema file to model the database | |
| generator client { | |
| provider = "prisma-client-js" | |
| } | |
| datasource db { | |
| provider = "postgresql" | |
| url = env("DATABASE_URL") // the DATABASE_URL is stored in .env file | |
| } | |
| model Cat { | |
| id Int @default(autoincrement()) @id | |
| name String | |
| age Int | |
| breed String | |
| } | |
| // To generates SQL files and also runs them on the configured database, run following command | |
| npx prisma migrate dev --name init | |
| // Create a Database service to interact with the Prisma Client API | |
| @Injectable() | |
| export class PrismaService extends PrismaClient implements OnModuleInit { | |
| async onModuleInit() { | |
| await this.$connect(); | |
| } | |
| async enableShutdownHooks(app: INestApplication) { | |
| this.$on('beforeExit', async () => { | |
| await app.close(); | |
| }); | |
| } | |
| } | |
| // In service layer, we inject the DatabaseService | |
| constructor(private prisma: PrismaService) {} | |
| // We can perform database operation via Prisma client api as below | |
| // Please note that we use Prisma Client’s generated types, like the "Cat" | |
| async cat( | |
| catWhereUniqueInput: Prisma.CatWhereUniqueInput, | |
| ): Promise<Cat | null> { | |
| return this.prisma.cat.findUnique({ | |
| where: catWhereUniqueInput, | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment