Web backstage service development -- a simple select for database query

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';

export class Person {
    id: number;

    @Column({ length: 100 })
    name: string;

    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';

export class PersonService {
        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';

  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';

export class V1Controller {
        private readonly personService: PersonService
    ) { }
    sayHello(@Param() params) {
        return `Hello Controller ${params.id}`;

    sayHi(@Body() hiDto: HiDto, @Param() params) {
        return hiDto;

    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.

Keywords: Database npm MySQL SQL

Added by Nytemare on Wed, 13 Nov 2019 19:53:28 +0200