preface

This article will document how NestJs connects to a database, not what. A server application that doesn’t connect to a database just writes Hello World. As for the database or choose MySQL, king way! Don’t ask Oracle, ask is collect money. As for the connection tool, here choose the TypeORM recommended by NestJs, of course, here is completely free ah, if some students like other tools is also completely ok.

Environment to prepare

MySQL

If you want to connect to a database, you have to have a database. Here I directly use my own cloud database, students who have a personal server suggest directly use remote, students who do not have a MySQL server can also install a local server, the installation method is not introduced here, you can ask Baidu.

  • Create a database and a table

First we create a new test library, and then we create a new user table in that library. BTW, here in fact can use visual tools to operate ha, personal feeling better use or Navicat, I here because it is not convenient to install, so direct access to the service.

This is what the table looks like, and then we insert a test data into the table so that we can test the database connection later.

At this point, database preparation is almost complete.

TypeORM

TypeORM is a commission of New Window (ORM) framework that runs on NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, Expo and Electron platforms. Works with TypeScript and JavaScript (ES5,ES6,ES7,ES8). Its goal is to always support the latest JavaScript features and provide additional features to help you develop any application that uses a database, whether it’s a small application with just a few tables or a large enterprise application with multiple databases. Unlike all other JavaScript ORM frameworks out there, TypeORM supports Active Record [(active-record-data-mapper.md#what-is-the-active-record-pattern) and data mapper modes, This means you can write high-quality, loosely-coupled, extensible, maintainable applications in the most efficient way possible. — TypeORM Chinese document

The definitions and methods of some modifiers will not be described in detail in this article. If you have any questions, please refer to TypeORM Chinese documentation

  • The installation
# yarn
@nestjs/typeorm typeorm mysql

#npm
npm install --save @nestjs/typeorm typeorm mysql
Copy the code

Project configuration

Create the entity

We will first create the Entities folder under the root path of the project, where the subsequent eneity files will be placed. Modules can also be differentiated according to business.

Then we create a new user.eneity. Ts file

  • user.entity.ts
import { Column, Entity, PrimaryGeneratedColumn, BaseEntity } from 'typeorm';

@Entity(a)export class UserEntity extends BaseEntity {
  // Add the primary key
  @PrimaryGeneratedColumn(a)id: number;

  / / column
  @Column({ type: 'varchar'.name: 'userName' })
  userName: string;

  @Column({ type: 'varchar'.name: 'userPwd' })
  // Key can be customized to be used in the project
  userPwd: string;
}
Copy the code

If you don’t need to do a Column name mapping, you can actually abbreviate it to @column (type), and you don’t want to omit type. As for inherited BaseEneity entities, these are the base entities provided by TypeORM, with some simple CRUD methods wrapped in them that should be easy to understand for those of you who have been exposed to Hibernate. Interested students can also go to see what methods are encapsulated in this entity, some simple business may be used.

Database Configuration

If you want to use the database, you must connect first. There are two ways to do this. This can be done using configuration files or directly in app.moudle.ts.

  • The configuration file

Add the ormconfig.json file in the root path of the project

{
    "type": "mysql".// Database type
    "host": "localhost".// Database address
    "port": 3306.// The port number is 3306 by default
    "username": "test"./ / user name
    "password": "test"./ / password
    "database": "test".// The database to connect to
    "synchronize": true.// The database synchronizes with the entity (if a new field is added to the entity, then the corresponding table of the database will be automatically inserted)
    "entities": ["src/entity/**/*.ts"].// Entity scan path
}
Copy the code

Other configuration items are not detailed here, you can refer to the documentation as required

  • app.module.ts

I did it this way, and configuring dynamic paths in the configuration file is a bit more complicated ~~

.import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({ // The configuration is written here
      type: 'mysql'.host: '* * *. * * *. * * *. * * *'.port: 3306.username: 'root'.password: '* * * * * * * * * * * *'.database: 'test'.entities: [__dirname + '/**/*.entity{.ts,.js}'].synchronize: true,}),... ] . })export class AppModule {}
Copy the code

PS:… Represents unchanged code, not true…

Add test interface

  • user.module.ts
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { UserEntity } from '@/entities/system/user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forFeature([UserEntity])],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}
Copy the code

PS2: Each entity file needs to be imported in its corresponding module and registered with TypeOrmModule.forfeature ()

  • user.service.ts

Here we inject entities and write a test method

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '@/entities/system/user.entity';

@Injectable(a)export class UserService {
  // Inject entities into the constructor
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ){}...// Add a getAll method here to test the configuration
  async getAllUserTest(): Promise<UserEntity[]> {
    // You can also use the Read method provided in BaseEntity, but it is recommended that you write your own SQL
    return await this.userRepository.query('select * from user'); }}Copy the code
  • user.controller.ts

Finally, add a test interface to the Controller

.@Controller('user')
@ApiTags('User action')
export class UserController {...@Get('get_all_list')
  findAll(): any {
    return this.userService.getAllUserTest(); }}Copy the code

test

Start the project by running YARN Start :dev and then request the interface you just defined from the tool

OK, you can see that the correct result is returned normally. So that’s the end of this article

PS: Next episode: Introduce JWT for login verification