Created
January 15, 2021 10:33
-
-
Save kevinvdburgt/5653fd567135545f6cf0529d5006a6e3 to your computer and use it in GitHub Desktop.
Prisma service using knex migrations.
This file contains 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 knex from 'knex'; | |
import knexfile from './knexfile'; | |
@Injectable() | |
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { | |
/** | |
* Waits for the database to be available. | |
*/ | |
private async waitForDatabase(): Promise<void> { | |
while (true) { | |
try { | |
const database = knex(knexfile); | |
await database.raw('SELECT 1 + 1;'); | |
await database.destroy(); | |
break; | |
} catch (error) { | |
// Database connection failed | |
await new Promise((resolve) => setTimeout(resolve, 1500)); | |
} | |
} | |
} | |
/** | |
* Run migrations. | |
*/ | |
private async runMigrations(): Promise<void> { | |
const database = knex(knexfile); | |
const [, migrations]: [null, { file: string; directory: string }[]] = await database.migrate.list(); | |
if (migrations.length > 0) { | |
await database.migrate.latest(); | |
} | |
await database.destroy(); | |
} | |
async onModuleInit(): Promise<void> { | |
await this.waitForDatabase(); | |
await this.runMigrations(); | |
await this.$connect(); | |
} | |
async onModuleDestroy(): Promise<void> { | |
await this.$disconnect(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment