前言
nest是一款兼容typescript和javascript的node.js框架.本文使用nest的一些基本模塊,來搭建一個簡單的web API CURD應用程序。typeORM是一款比較成熟的對象關係映射器,它是由typescript寫的。nest和typeORM的具體介紹,能夠查看官方文檔。javascript
項目搭建
使用CLI搭建project:java
npm i -g @nestjs/cli nest new nest-app
這樣就建立了一個nest-app項目,建立完成後,在src文件夾中包含如下幾個核心文件:node
src ├── app.controller.ts ├── app.module.ts └── main.ts
main.ts問項目啓動文件,默認監聽端口3000,根模塊app.module.ts,路由實例app.controller.ts.mysql
如今執行如下命令運行項目:git
npm run start
啓動後,在瀏覽器中輸入localhost:3000,能夠看到Hello world.github
typeORM的使用
安裝typeorm:web
npm install --save @nestjs/typeorm typeorm mysql
typeorm支持多種數據庫,本項目使用的是mysql。sql
建立實體employee和company,文件目錄:typescript
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:
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
歡迎小夥伴多來交流!^_^