/nestjs-drizzle

A NestJS module for integrating DrizzleORM with Postgres, MySQL, SQLite, Turso and Planetscale drivers

Primary LanguageTypeScriptMIT LicenseMIT

Nest Logo

A NestJS module for integrating Drizzle ORM

Nrwl Nx

CodeFactor Grade NPM Discord

Table of Contents

Installation

There is a separate module for each one of the major database drivers supported by the DrizzleORM. You can install them via your preferred package manager.

# PostgresJS
npm install @knaadh/nestjs-drizzle-postgres drizzle-orm postgres

# Node-Postgres
npm install @knaadh/nestjs-drizzle-pg drizzle-orm pg

# MySQL2
npm install @knaadh/nestjs-drizzle-mysql2 drizzle-orm mysql2

# Better-SQLite3
npm install @knaadh/nestjs-drizzle-better-sqlite3 drizzle-orm better-sqlite3

# Turso
npm install @knaadh/nestjs-drizzle-turso drizzle-orm @libsql/client

# PlanetScale
npm install @knaadh/nestjs-drizzle-planetscale drizzle-orm @planetscale/database

Usage

Import the Drizzle module of the respective database driver and pass an options object to initialize it as shown in the example below:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as schema from '../db/schema';
import { DrizzleBetterSQLiteModule } from '@knaadh/nestjs-drizzle-better-sqlite3';
@Module({
  imports: [
    DrizzleBetterSQLiteModule.register({
      tag: 'DB_DEV',
      sqlite3: {
        filename: 'demo.db',
      },
      config: { schema: { ...schema } },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

You can inject the Drizzle instances using their respective tag specified in the configuration

import { Inject, Injectable } from '@nestjs/common';
import * as schema from '../db/schema';
import { LibSQLDatabase } from 'drizzle-orm/libsql';
@Injectable()
export class AppService {
  constructor(
    @Inject('DB_DEV') private drizzleDev: LibSQLDatabase<typeof schema>
  ) {}
  async getData() {
    const books = await this.drizzleDev.query.books.findMany();
    const authors = await this.drizzleDev.query.authors.findMany();
    return {
      books: books,
      authors: authors,
    };
  }
}

You can read the detailed documentation of each of the module from the links given below

Documentation

License

This package is MIT licensed.