Article from Geek Forum
Step 1: create module s and service s
Execute the following command at the command line to create the module and service named Person.
nest g module person nest g service person
In this case, the directory named person will be generated automatically
Step 2 create entity
Create the file person.entity.ts in the person directory and write the following
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Person { @PrimaryGeneratedColumn() id: number; @Column({ length: 100 }) name: string; @Column('int') age: number; }
Step 3 modify service
Modify person.service.ts as follows
import { Injectable } from '@nestjs/common'; import { Repository } from 'typeorm'; import { Person } from './person.entity'; import { InjectRepository } from '@nestjs/typeorm'; @Injectable() export class PersonService { constructor( @InjectRepository(Person) private readonly personRepo: Repository<Person> ) { } findAll(): Promise<Person[]> { return this.personRepo.find(); } }
Step 4 modify the module
Modify person.module.ts as follows
import { Module } from '@nestjs/common'; import { PersonService } from './person.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Person } from './person.entity'; @Module({ imports: [TypeOrmModule.forFeature([Person])], providers: [PersonService], exports: [PersonService] // Here, we need to export PersonService, because we need to use it in root module }) export class PersonModule { }
Step 5 modify the controller
Modify V1 controller and add content
import { Controller, Get, Param, Post, Body } from '@nestjs/common'; import { HiDto } from 'src/v1/dto/hi-dto'; import { PersonService } from 'src/person/person.service'; import { Person } from '../person/person.entity'; @Controller('v1') export class V1Controller { constructor( private readonly personService: PersonService ) { } @Get('/hello/:id') sayHello(@Param() params) { return `Hello Controller ${params.id}`; } @Post('/hi/:id') sayHi(@Body() hiDto: HiDto, @Param() params) { console.log(hiDto); console.log(params.id); return hiDto; } @Get('/person/list') async getPersonList(): Promise<Person[]> { return this.personService.findAll(); } }
Step 6 operation
npm run start
Visit localhost:3000/v1/person/list in browser
Be careful:
You need to create the database you want to use in MySQL through Heidi SQL;
In addition, you will notice that the person table will be created automatically in the database after the program runs.