This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

This article describes how to use Sequelize in NestJS to perform operations on user tables

First download the relevant packages

$ npm install --save @nestjs/sequelize sequelize sequelize-typescript mysql2
$ npm install --save-dev @types/sequelize
Copy the code

Import the SequelizeModule into the root AppModule

// app.module
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './users/user.model'; // Define the User model, as defined later
@Module({
  imports: [
    SequelizeModule.forRoot({
      dialect: 'mysql'.Sequelize supports Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It also has requirements on the database version. You can go to the official website
      host: '127.0.0.1'./ / host IP
      port: 3306.// Database port mysql uses port 3306 by default
      username: 'xxx'.// Database user name
      password: 'xxx'.// Database password
      database: 'xxx'.// Specific database
      models: [User], // To start using the 'User' model, we need to let 'Sequelize' know it exists by inserting it into the 'models' array of the' forRoot() 'method option.
    }),
    UsersModule,
  ],
})
export class AppModule {}
Copy the code

Defining the User model

// users/user.model
import { Column, Table, Model } from 'sequelize-typescript';
@Table({
  tableName: 'admin_user'.// Specify the table name. The default is to generate SQL using the model name (User).
  timestamps: false.// The default is true. When true, createdAt and updatedAt fields will be queried
})
export class User extends Model<User> {
  @Column
  username: string;
  @Column
  password: string;
  @Column
  email: string;
  @Column
  mobile: string;
  @Column
  create_time: Date;
}
Copy the code

To use the user model in user.serveice, you need to inject user.mudule

// users/user.module
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './user.model';
@Module({
  controllers: [UsersController],
  providers: [UsersService],
  imports: [SequelizeModule.forFeature([User])], // Make sure the service injects UsersRepository into UsersService with the @injectrepository () decorator:
})
export class UsersModule {}
Copy the code

After injection, you can attach the User model to the UserService in the constructor. Facilitate subsequent database operations (in this example, only the [search] operation is shown. The addition, deletion and modification of a single table are almost the same. Go to sequelize to learn how to do this.)

// users/user.service
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { User } from './user.model';

@Injectable()
export class UsersService {
  constructor( 
    @InjectModel(User)
    private userModel: typeof User,
  ) {}

  findAll(): Promise<User[]> {
    return this.userModel.findAll(); // Use userModel to query all data
  }

  find(id: string): Promise<User> {
    return this.userModel.findOne({ where: { id } }); // Select with userModel constraints}}Copy the code

Finally, take a look at the code in the Controller section. Go through the process

// users/user.controller
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './user.model';

@Controller('users')
export class UsersController {
  constructor(private usersService: UsersService) {}
  @Get('users')
  async findAll(): Promise<User[]> {
    const r = await this.usersService.findAll();
    console.log(r);
    return r;
  }
  @Get(':id')
  async findOne(@Param() params): Promise<User> {
    const { id } = params;
    return await this.usersService.find(id); }}Copy the code

Postman requests a test

X Chinese document Nestjs 8.x Chinese document