nest.js + typeORM:基本使用
前言
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
歡迎小夥伴多來交流!^_^
nest.js + typeORM:基本使用