前言
nest是一款兼容typescript和javascript的node.js框架.本文使用nest的一些基本模块,来搭建一个简单的web后端CURD应用程序。typeORM是一款比较成熟的对象关系映射器,它是由typescript写的。nest和typeORM的具体介绍,可以查看官方文档。
项目搭建
使用CLI搭建project:
npm i -g @nestjs/cli nest new nest-app
这样就创建了一个nest-app项目,创建完成后,在src文件夹中包含以下几个核心文件:
src ├── app.controller.ts ├── app.module.ts └── main.ts
main.ts问项目启动文件,默认监听端口3000,根模块app.module.ts,路由实例app.controller.ts.
现在执行以下命令运行项目:
npm run start
启动后,在浏览器中输入localhost:3000,可以看到Hello world.
typeORM的使用
安装typeorm:
npm install --save @nestjs/typeorm typeorm mysql
typeorm支持多种数据库,本项目使用的是mysql。
创建实体employee和company,文件目录:
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[] }
在typeorm中都是通过装饰器来指定对象映射关系,本项目实体中目前主要使用仅使用了自增长主键,数据列,一对多关系等基本功能,在定义实体对象之间的关系时,关系一定要清楚,本例使用了cascade,可以用于级联删除级联保存操作。注意:级联删除和级联保存仅在save()时会生效,在insert()时无效。
创建employee模块
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 { }
在employee.module.ts中TypeOrmModule.forFeature()是用于动态获取模块对象。在employee.controller.ts使用了基本的路由配置方式。
模块注入,数据库连接信息配置
在根目录中注入employee模块:
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 { }
可以看到,在imports中使用typeormmodule.forRoot()用于动态返回typeormmodule,typeormmodule连接数据库的方式有多种,可以使用配置文件,也可以在forRoot()中传入options参数信息,本例使用配置文件,在src目录下添加ormconfig.json文件:
{ "type": "mysql", "host": "localhost", "port": 3306, "username": "root", "password": "root", "database": "nest-app", "entities": ["src/**/**.entity{.ts,.js}"], "synchronize": true }
至此一个基本的带有employee的创建和查询功能的service程序已搭建完毕,浏览器输入:localhost:3000/employee/create看看效果吧。
源码github
欢迎小伙伴多来交流!^_^
原文地址:https://www.cnblogs.com/novak12/p/9249688.html