Use Drizzle in NestJS app

Hi everyone ! I am new to both drizzle and NestJS and was wondering if there was any recipe out there to use Drizzle in NestJS (I couldn't find anything) should I create a service or something ? (as Prisma ?)
L
Louistiti300d ago
Okay so basically what I did is this : drizzle.module.ts
import { Module } from '@nestjs/common';
import { DrizzleService } from './drizzle.service';

@Module({
providers: [DrizzleService],
exports: [DrizzleService],
})
export class DrizzleModule {}
import { Module } from '@nestjs/common';
import { DrizzleService } from './drizzle.service';

@Module({
providers: [DrizzleService],
exports: [DrizzleService],
})
export class DrizzleModule {}
drizzle.service.ts
import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import { Injectable } from '@nestjs/common';
import postgres, { Sql } from 'postgres';
import * as process from 'process';
import { sql } from 'drizzle-orm';

@Injectable()
export class DrizzleService {
private db: PostgresJsDatabase;
private queryClient: Sql<{}>;

constructor() {
this.connect();
}

private async connect(): Promise<void> {
const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
throw new Error('No environment variable DATABASE_URL');
}
this.queryClient = postgres(connectionString);
this.db = drizzle(this.queryClient);

await this.clearDb();
}

public getDb(): PostgresJsDatabase {
return this.db;
}

public async clearDb(): Promise<void> {
const query = sql<string>`SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE';
`;

const tables = await this.db.execute(query);

for (let table of tables) {
const query = sql.raw(`TRUNCATE TABLE ${table.table_name} CASCADE;`);
await this.db.execute(query);
}
}
}
import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import { Injectable } from '@nestjs/common';
import postgres, { Sql } from 'postgres';
import * as process from 'process';
import { sql } from 'drizzle-orm';

@Injectable()
export class DrizzleService {
private db: PostgresJsDatabase;
private queryClient: Sql<{}>;

constructor() {
this.connect();
}

private async connect(): Promise<void> {
const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
throw new Error('No environment variable DATABASE_URL');
}
this.queryClient = postgres(connectionString);
this.db = drizzle(this.queryClient);

await this.clearDb();
}

public getDb(): PostgresJsDatabase {
return this.db;
}

public async clearDb(): Promise<void> {
const query = sql<string>`SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE';
`;

const tables = await this.db.execute(query);

for (let table of tables) {
const query = sql.raw(`TRUNCATE TABLE ${table.table_name} CASCADE;`);
await this.db.execute(query);
}
}
}
app.module.ts
import { Module } from '@nestjs/common';

import { AppController } from './app.controller';
import {DrizzleModule} from "./config/drizzle/drizzle.module";

@Module({
imports: [DrizzleModule, ...your modules],
controllers: [AppController],
providers: [...your providers],
})
export class AppModule {}
import { Module } from '@nestjs/common';

import { AppController } from './app.controller';
import {DrizzleModule} from "./config/drizzle/drizzle.module";

@Module({
imports: [DrizzleModule, ...your modules],
controllers: [AppController],
providers: [...your providers],
})
export class AppModule {}
P
parmetra199d ago
Hello! Is this a working solution?
L
Louistiti199d ago
Yes it works
O
olup199d ago
we also make the module global for easyer use
L
Louistiti195d ago
What does that change exactly ? (I am new to NestJS)
O
olup195d ago
You just don't have to import it in module files
L
Louistiti194d ago
Ohhhh awesome !
Z
zzao107d ago
Bro, I try this implementations and I can't run the app, i got this error :
this.queryClient = postgres(connectionString);
TypeError: (0 , postgres_1.default) is not a function
this.queryClient = postgres(connectionString);
TypeError: (0 , postgres_1.default) is not a function
Obs: My connectionString is rigth
M
Mithlesh105d ago
GitHub
GitHub - knaadh/nestjs-drizzle: A NestJS module for integrating Dri...
A NestJS module for integrating DrizzleORM with Postgres, MySQL, SQLite, Turso and Planetscale drivers - GitHub - knaadh/nestjs-drizzle: A NestJS module for integrating DrizzleORM with Postgres, My...
Want results from more Discord servers?
Add your server
More Posts
[Solved] Transforming const to the configured target environment ("es5") is not supported yetSo I had a old project, and I copied the `DATABASE_URL` and on created a basic drizzle project and `Placeholders in inserting: db.insert().values(placeholder('example'))Hey, how do I add placeholders inside the values of an insert prepare statement? I get an typeerror Can I add a Unique constraint to a column?I couldn't find an option for that in the docs. I'm assuming Drizzle doesn't support that. So, coul"Cannot parse date or time" using AWS Data API, aurora postgresI'm trying drizzle-orm (with sst) and aurora pg thru aws data api, when trying to insert a Date valuFiltering against a relationI have a orgs table that have a many to many relation with a users table. while querying with the fGet type for select query?Hey guys, is there a way to infer the "select" type for a given table? for example: ```ts async getorderBy related table columnGiven a relational query such as ``` const matchResult = await db.query.matches.findMany({ Soft Delete StrategyI'm a person of eloquent taste; one who prefers the soft delete. With the current feature set of driColumns that not allowed to updatedHi guys, I'm looking for a proper way to declare SQL schema and its `InferModel` types when there'rExecute sql with '?' as parameterHello everyone. Please, how do I execute a sql that uses as a parameter the character '?' ? For examForeign Key Reference to auth Schema Not Generated in CodeI'm having an issue with my Drizzle-ORM code where the foreign key reference to the 'auth' schema isHow can I add a Prefix Index?I migrated from Prisma, and I have a column with `varchar(2000)` which I indexed with `@@index([coluconnect to local postgresDoes anyone knows how to connect to a local pg with neon? I tried: ``` import { neon, neonConfig } defaultNow(), onUpdateNow() not available on the datetime data typeI'm able to build this into my database, but I'm not able to express it through drizzle. What gives?NeonDbError: db error: ERROR: permission denied for schema drizzleCreated a new database on neon.tech today and trying to run migrations ``` // src/db/migrate.ts impHow can I filter on a joined table field (nested value) with the relational query syntax?☝🏻How to implement a where clause on a joined table with the new relation builder?This was my original query, the big problem is that it returns as many rows as there are messages inError when deploying migrations with GH Action in Cloudflare D!I'm trying to run migrations within a turborepo against a Cloudflare D1 instance. The command to run0.27.2 mysql:pushmysql:push in 0.27.2 is trying to alter my primaryKey with no schema changes. it also seems to try aCreating an abstract base repositoryHi, I'm trying to create a base repository for my application but can't make it work. Is it even pos