Record some learning and sharing of using Nest. js to build personal blog. Through using and taking notes, I hope I can learn more solid and master knowledge more skillfully. The project has been set up last time. Today we will connect the database and modify the data through the interface.

start

Mysql > install mysql from nestJS

npm install --save @nestjs/typeorm typeorm mysql2
Copy the code

With the above installation, we have integrated the mysql library into NestJS and used TypeOrm to operate.

  • Mysql2:node.jsTo operatemysqlThe library;
  • Typeorm: aormLibrary, can be understood as the object and table to do a mapping relationship, to facilitate the operation;
  • @ nestjs/typeorm:nestjsBased on thetypeormThe encapsulation.

use

Before using TypeOrm to operate on the database, we need to establish a connection with the local database (navicat can check whether the connection is normal), as shown in the following figure:

After the test is successful, we can start working with the database in NestJS.

Connecting to a Database

It’s very easy to connect to the database in nestjs, just insert a simple configuration in app.module.ts as follows:

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql'.host: 'localhost'.port: 3306.username: 'root'.password: 'password'.database: 'myblog'.entities: ['dist/**/*.entity{.ts,.js}'].// Do not change the path
      synchronize: true})],controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Copy the code

So, you have the mysql database connection configured. But then there’s the question, how do we use it to manipulate data? The next step is to introduce entity classes, an important concept in TypeOrM.

Entity class

Entity class is a mapping of the database table structure. By mapping each field into the attributes of the object, and then influencing the database in the way of operating the object, the way of operating the database has changed from writing SQL to calling API, which is more convenient for developers.

The simplest entity class would look like this:

import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from 'typeorm';
import Article from './article.entity';

@Entity({
  name: 'tag',})class Tag {
  @PrimaryGeneratedColumn()
  id = 0;

  @Column({
    type: 'varchar'.length: 20.comment: 'Tag name',
  })
  title = ' ';

  @Column({
    type: 'varchar'.length: 20.comment: 'Creation time',
  })
  createTime = ' ';
}

export default Tag;
Copy the code

The @Entity decorator above indicates that the object is an Entity class maintained by TypeOrM, with each field decorated by @Column. With this in mind, we are ready to start working with the database based on NestJS.

When we have defined the entity class, startnestjsAfter service, it will automatically help us to create the corresponding table.

Operating the Mysql

Nestjs provides a Repository object for operating on a database, but you need to register it with the corresponding Module before using it.

// tag.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import Tag from 'src/entity/tag.entity';
import { TagController } from './tag.controller';
import { TagService } from './tag.service';

@Module({
  imports: [TypeOrmModule.forFeature([Tag])],
  controllers: [TagController],
  providers: [TagService]
})
export class TagModule {}

Copy the code

Imports the corresponding module. Then you can go to tag.service.ts and write mysql code:

// tag.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Tag from 'src/entity/tag.entity';
import { Repository } from 'typeorm';

@Injectable(a)export class TagService {
  constructor(
    @InjectRepository(Tag)
    private readonly tagRepository: Repository<Tag>
  ) {}
  
  async find() {
    return await this.tagRepository.find(); }}Copy the code

This allows us to manipulate the database using the tagRepository defined object. A Repository is a per-entity Repository that allows you to easily manipulate databases, which is the idea behind ORM manipulation databases.

Call the interface through the browser

After completing the above steps, you can implement a simple get interface to query the contents of the tag table, mainly write controller and service class, as follows:

tag.controller.ts

import { Controller, Get, Req, Res } from '@nestjs/common';
import { TagService } from './tag.service';

@Controller('tag')
export class TagController {
  constructor(private readonly tagService: TagService) {}

  @Get('/list')
  async getTagList(@Req() req, @Res() res) {
    const ret = await this.tagService.find();

    res.json({
      code: 200.data: ret }); }}Copy the code

tag.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Tag from 'src/entity/tag.entity';
import { Repository } from 'typeorm';

@Injectable(a)export class TagService {
  constructor(
    @InjectRepository(Tag)
    private readonly tagRepository: Repository<Tag>
  ) {}
  
  async find() {
    return await this.tagRepository.find(); }}Copy the code

At this point, if the operation is ok, visit /tag/list and you will see the following result:

Consistent with the database data, no problem:

conclusion

Today, having finished using nestJS to manipulate the database, I learned the following:

  1. nestCan be found inapp.module.tstheimportsIt introducedmysqlThe configuration;
  2. @EntityDecorator, a key to implementing entity classes:
    1. @Column: represents a database field;
    2. @PrimaryGeneratedColumn(): represents the auto-increment primary key field of data;
  3. nestjsBased on thetypeormoperationmysqlA process of:
    1. inapp.module.tsDo a good job of configuration, start the service will automatically build a table;
    2. In a module, passTypeOrmModule.forFeatureIntroducing corresponding entities;
    3. inserviceInside, through@InjectRepositoryInject correspondingRepositoryObject;
    4. Use entity mappingRepositorycallApiOperate the database.

To be continued…