Article From:https://www.cnblogs.com/novak12/p/9249688.html

Preface

nestIt is a node.js framework compatible with typescript and JavaScript. In this paper, we use some basic modules of nest to build a simple web CURD application. TypeORM is a relatively mature object relational mapping device.It’s written by typescript. The introduction of nest and typeORM can view official documents.

Project construction

Using CLI to build project:

 npm i -g @nestjs/cli
 nest new nest-app

This creates a nest-app project. After creation, the following core files are included in the SRC folder:

src
├── app.controller.ts
├── app.module.ts
└── main.ts

main.tsAsk the project startup file, default listening port 3000, root module app.module.ts, routing instance app.controller.ts.

Now execute the following command to run the project:

npm run start

After startup, enter localhost:3000 in the browser, you can see Hello world.

typeORMUse

Install typeorm:

npm install --save @nestjs/typeorm typeorm mysql

typeormSupport for multiple databases. This project uses mysql.

Create the entity employee and company, the file directory:

entities
├── employee.entity.ts
├── company.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinTable } from 'typeorm';
import { Company } from './company.entity'
@Entity()
export class Employee {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    age: number

    @Column()
    address: string

    @ManyToOne(type => Company, company => company.employees, { cascade: true })
    @JoinTable()
    company: Company
}

company.entity.ts:

import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { Employee } from './employee.entity'
@Entity()
export class Company {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany(type => Employee, employee => employee.company)
    employees: Employee[]
}

In typeorm, the object mapping relationship is specified by the decorator. The main use of this project entity is the use of the basic functions such as self growth key, data column, and one to many relationships. The relationship must be clear when defining the relationship between entity objects, and this example uses cascade.For cascading delete cascaded save operations. Note: cascading deletions and cascading guarantees will only take effect when save () is applied, but not at insert ().

Create a employee module

employee
├── employee.controller.ts
├── employee.module.ts
└── employee.service.ts

employee.service.ts:

import { Injectable } from '@nestjs/common';
import { Employee } from '../entities/employee.entity'
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Company } from '../entities/company.entity'

@Injectable()
export class EmployeeService {

    constructor(@InjectRepository(Employee)
    private readonly employeeRepository: Repository<Employee>) { }
    root(): string {
        return 'Hello World!';
    }
    async create(): Promise<string> {
        let employee = new Employee();
        let company = new Company();
        company.name = 'asc';
        employee.name = 'novak';
        employee.age = 20;
        employee.address = 'shanghai';
        employee.company = company;

        return this.employeeRepository.save(employee)
            .then(res => {
                return 'create employee ...done'
            })
            .catch(err => {
                return err
            });
    }

    async findOne(name: string): Promise<Employee> {
        return await this.employeeRepository.findOne({ name: name });
    }
}
employee.controller.ts:
import { Get, Controller,Param } from ‘@nestjs/common’;
import { EmployeeService } from ‘./employee.service’;
import { Employee } from ‘entities/employee.entity’;

 

@Controller(’employee’)
export class EmployeeController {
constructor(private readonly employeeService: EmployeeService) {}

 

@Get()
root():string{
console.log(123)
return this.employeeService.root();
}

 

@Get(‘findOne/:name’)
async findOne(@Param() params):Promise<Employee>{
console.log(params.name);
return this.employeeService.findOne(params.name);
}

 

@Get(‘create’)
async create():Promise<string>{
console.log(‘1323’)
return this.employeeService.create();
}
}

employee.module.ts:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EmployeeController } from './employee.controller'
import { EmployeeService } from './employee.service'
import { Employee } from '../entities/employee.entity'

@Module({
    imports: [TypeOrmModule.forFeature([Employee])],
    providers: [EmployeeService],
    controllers: [EmployeeController]
})
export class EmployeeModule {
  
}
In employee.module.ts, TypeOrmModule.forFeature () is used to dynamically acquire module objects. The basic routing configuration is used in employee.controller.ts.

Module injection, database connection information configuration

Inject the employee module in the root directory:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import {EmployeeModule} from './employee/employee.module'

@Module({
  imports: [
    TypeOrmModule.forRoot(),
    EmployeeModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

As you can see, using typeormmodule.forRoot () in imports for dynamic return to typeormmodule, typeormmodule connects databases with a variety of ways to use configuration files or in forThe options parameter information is introduced into Root (). This example uses a configuration file to add ormconfig.json files in the SRC directory.

{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "root",
    "password": "root",
    "database": "nest-app",
    "entities": ["src/**/**.entity{.ts,.js}"],
    "synchronize": true
  }

At this point, a basic service program with the creation and query capabilities of employee has been built, and the browser is entered: localhost:3000/employee/create to see the effect.

Source code GitHub

Welcome small partners to exchange! Square

Similar Posts:

Link of this Article: Basic use of nest.js + typeORM:

One Reply to “Basic use of nest.js + typeORM:”

Leave a Reply

Your email address will not be published. Required fields are marked *