This is the 18th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

The database

typeorm

The dependencies need to be installed first

npm install –save @nestjs/typeorm typeorm mysql2

Then introduce it to app.module.ts

Introducing way

Method 1
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql'.host: 'localhost'.port: 3306.username: 'root'.password: 'root'.database: 'test'.entities: [].synchronize: true,})]})export class AppModule {}
Copy the code
Way 2

The root directory creates ormconfig.json so that you don’t have to pass the configuration object to forRoot

{
  "type": "mysql"."host": "localhost"."port": 3306."username": "root"."password": "root"."database": "test"."entities": ["dist/**/*.entity{.ts,.js}"]."synchronize": true
}
Copy the code

There’s one thing that needs to be commented on here

Static global paths (e.g. Dist //*.entity{.ts,.js}) are not available for Webpack hot overloading. **

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forRoot()],
})
export class AppModule {}

Copy the code

prisma

  1. npm install prisma –save-dev

npx prisma init

This command creates a new prisma directory that contains the following:

  • Schema. prisma: Specifies your database connection and includes the database schema
  • Env: A dotenv file, typically used to store your database credentials in a set of environment variables
datasource db {
  provider = "sqlite" // Database type
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

// Model is to define your data model. This is just an example

model User {
  id    Int     @default(autoincrement()) @id
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @default(autoincrement()) @id
  title     String
  content   String?
  published Boolean? @default(false)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}
Copy the code
/ / env file

DATABASE_URL="mysql://root:password@localhost:3306/tablename"
Copy the code

With the Prisma model, you can generate SQL migration files and run them against the database. Run the following command on the terminal:

npx prisma migrate dev –name init

Install and build Prisma client #

npm install @prisma/client

Create the prisma.service.ts file and add the code below it

import { INestApplication, Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient
  implements OnModuleInit {

  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit'.async() = > {awaitapp.close(); }); }}Copy the code

The onModuleInit is optional – if you leave it, Prisma will lazily connect to the database on its first call. We ignore onModuleDestroy because Prisma has its own close hook that breaks the connection. For more information about enableShutdownHooks, see the issue enableShutdownHooks

Next, write the service code for your situation

For example, create a new file named user.service.ts and add the following code to it:

import { Injectable } from '@nestjs/common';
import { PrismaService } from './prisma.service';
import {
  User,
  Prisma
} from '@prisma/client';

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) {}

  async user(userWhereUniqueInput: Prisma.UserWhereUniqueInput): Promise<User | null> {
    return this.prisma.user.findUnique({
      where: userWhereUniqueInput,
    });
  }

  asyncusers(params: { skip? : number; take? : number; cursor? : Prisma.UserWhereUniqueInput; where? : Prisma.UserWhereInput; orderBy? : Prisma.UserOrderByInput; }) :Promise<User[]> {
    const { skip, take, cursor, where, orderBy } = params;
    return this.prisma.user.findMany({
      skip,
      take,
      cursor,
      where,
      orderBy,
    });
  }

  async createUser(data: Prisma.UserCreateInput): Promise<User> {
    return this.prisma.user.create({
      data,
    });
  }

  async updateUser(params: {
    where: Prisma.UserWhereUniqueInput; data: Prisma.UserUpdateInput; }) :Promise<User> {
    const { where, data } = params;
    return this.prisma.user.update({
      data,
      where,
    });
  }

  async deleteUser(where: Prisma.UserWhereUniqueInput): Promise<User> {
    return this.prisma.user.delete({ where, }); }}Copy the code

And then call it in controller