VitNode
Database

Service

How to use database in service

To get access to the database in a service, you need to inject the DatabaseService into the service constructor.

show.service.ts
import { Injectable } from "@nestjs/common";
import { DatabaseService } from "@/database/database.service";
 
@Injectable()
export class ExampleService {
  constructor(private readonly databaseService: DatabaseService) {} 
}

Query

VitNode supports query by Drizzle ORM in service to get data with relations from the database.

show.service.ts
import { Injectable } from "@nestjs/common";
import { DatabaseService } from "@/database/database.service";
 
@Injectable()
export class ExampleService {
  constructor(private readonly databaseService: DatabaseService) {}
 
  async create(): Promise<string> {

    const data = await this.databaseService.db.query.core_test_table.findMany({
      where: (table, { eq }) => eq(table.id, 1)
    });
  }
}

Check Drizzle ORM documentation - Query for more information.

Select

await this.database.db.select().from(core_test_table);

Check Drizzle ORM documentation - Select for more information.

Insert

await this.database.db.insert(core_test_table).values({ name: "Andrew" });

Check Drizzle ORM documentation - Insert for more information.

Update

await this.database.db
  .update(core_test_table)
  .set({ name: "Mr. Dan" })
  .where(eq(core_test_table.name, "Dan"));

Check Drizzle ORM documentation - Update for more information.

Delete

await this.database.db.delete(core_test_table).where(eq(core_test_table.name, "Dan"));

Check Drizzle ORM documentation - Delete for more information.

Operations

Drizzle ORM documentation - Operations supports many operations like eq, neq, gt, gte, lt, lte, in, nin, like, ilike, is, isNot, between, notBetween, etc.

Joins

await this.database.db
  .select()
  .from(core_test_table)
  .join(core_test_table2)
  .on(eq(core_test_table.id, core_test_table2.id));

Check Drizzle ORM documentation - Joins for more information.

Magic SQL

You can use magic SQL to create raw SQL query with Drizzle ORM.

import { sql } from "drizzle-orm";
const id = 69;
await db.execute(sql`select * from ${usersTable} where ${usersTable.id} = ${id}`);

Check Drizzle ORM documentation - Magic SQL for more information.

On this page