nestjs builds a simple backend to connect to mysql

introduce

This article refers to nestjs official documentation

After using the koa and express frameworks built with nodejs, I found that using the front-end syntax can also build a good back-end, and now it is gradually developing with typescript, I found that nestjs can support typescript well and carry out a Engineering development.

new

Before getting started, you can use nest's scaffolding to quickly build a nest project. (Make sure Node.js (>=10.13.0, except v13))

npm i -g @nestjs/cli
nest new project-name #project-name is the project name, a new nestjs project will be created in the current directory

When you create it, you will choose what to use as the package management tool. Here, npm is used by default.

After waiting for the completion, you can enter the project and use npm run start to run the project. (You can also use npm run start:dev to start a hot update.)

File introduction

After the project is created, the following files are automatically generated in src:

app.controller.ts

app.controller.spec.ts

app.module.ts

app.service.ts

main.ts

main.ts, as the project entry file, listens to port 3000 by default, and mounts the AppModule. According to these files automatically generated by nestjs, you can get a general idea of ​​how a nestjs project should be written.

module

Because AppModule is introduced in the entry file of main.ts, first let's look at the module file.

According to the above figure, you can see that the previous AppController and AppService files are passed through the AppModule module, which involves the very important concepts of nestjs, Controllers and Providers, which is like the classic MVC architecture of the backend, which layers the control layer and the service layer. Carry out, put all operations on the database in Providers (but not all Providers are used to operate the database), and the data logic to be returned to the front end is carried out in Controllers, and Module is mainly used to manage the control layer and the service layer, It is possible that multiple database operations need to be called in one interface, and in this case, it needs to be registered in Module.

The module management in the above figure will be used in the imports part of the current Module, and the ORM framework can also be used in combination with TypeOrm to operate the database.

In short, every time a new controller or provider is created, it needs to be introduced in the module, so that the nest can recognize it.

Controller

In the controller, mainly deal with the corresponding data to be returned to the client.

A basic interface can be implemented using routing.

//@Controller creates a controller with the path /text
@Controller('/text')
export class Ctroll{
    //This is done when sending a request with /text as the path and in the Get method.
    @Get()
    find(@Query()query){//Send it in the form of a query, that is, localhost:3000/text?a=1 The value of the query is {a:1}
        return query;
    }
}

Using the controller can receive three types of parameters, in addition to the query used above, there are param and body.

  • query is sent in the form of localhost:3000/text?a=1
  • param is sent in the form of localhost:3000/text/:id
@Get(':id') //send as path
find(@Param()param){
    return param
}
  • The body is sent in the form of an object (usually used for POST requests)

example:

//send data
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
//Receive data
@Post()
find(@Body()body){
    return body
}

At this time, if you don't need to operate the database, a simple back-end interface has been implemented. Of course, there are many functions such as setting the corresponding header and corresponding code, which must be understood through official documents.

Providers

Providers are a concept based on nestjs. Providers can be the service layer that operates the database, helpers, or others, mainly to provide some injected dependencies.

Before using Service, we can connect to the database first. Taking mysql as an example, we need to download the dependencies of mysql and typeorm first. Of course, typeorm is not necessary, that is, npm i mysql2 and npm install typeorm --save.

//app.module.ts
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserTable } from './entity/userTable.entity';
@Module({
    imports:[
        //Connect to the database
        // Connect to the database
    	TypeOrmModule.forRoot({
      	  type: 'mysql',
      	  host: 'ip address',
      	  port: port,
      	  username: 'user',
      	  password: 'password',
      	  database: 'surface',
      	  entities: [UserTable],//The added entity UserTable is in the code below
      	// Database synchronization update
      	synchronize: true,
    	}),
    ]
})

However, it is still mostly used for adding, deleting, modifying and checking the database. Providers generally start with @Injectable(), wrap them with classes, and use constructors to inject the data to be modified. After they are declared in the constructors, the functions can be called through this when the function is called.

//service
@Injectable()
export class TextService{
    constructor(
      @InjectRepository(UserTable) //userTable is an entity that uses typeorm, the code is below, if you don't know typeorm, you can check his official documentation
      private readonly userTableRepository: Repository<UserTable>, //Add private and read-only properties to prevent modification
    ){}
    async findAll(){
        return this.userTableRepository.find();//find is a method of typeorm, similar to SELECT * FROM userTable of sql statement;
    }
}
@Entity()
export class UserTable{
    @PrimaryGeneratedColumn()
  	id: number;
    @Column()
    userName:string
}

Of course, the above is the operations that can be performed after connecting to mysql. If there is no connection to mysql, nest will report an error directly.

Use service in controller

In nest, the mutual data is basically passed through the constructor, of course, these all need to be registered in the Module module.

import { TextService } from './financial_table.service';

@Controller('/text')
export class Ctroll{
    //Here is the Textservice
    constructor(private readonly textService: TextService) {},
    @Get()
    async find(){
        return await this.textService.findAll()
    }
}

In this way, the basic database operations are completed, and the most basic back-end interfaces can also be implemented. Of course, there are other functions such as pipeline verification using Pipe, which can be learned more through the official documentation.

Tags: MySQL Front-end Javascript

Posted by johnperkins21 on Mon, 17 Oct 2022 03:26:21 +1030