# Learning NestJS, Part3 ###### tags: `Nestjs` ## 學習資源 [NestJS: The Complete Developer's Guide](https://www.udemy.com/course/nestjs-the-complete-developers-guide/) on Udemy ## 使用TypeORM操作資料 ### 流程 1. 建立(entity_name).entity.ts的檔案 2. 從'typeorm'引入所需的decorator,ex: PrimaryGeneratedColumn、Entity、Column ``` // user.entity.ts import { AfterInsert, Entity, Column, PrimaryGeneratedColumn, AfterRemove, AfterUpdate, } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() email: string; @Column() password: string; @AfterInsert() logInsert() { console.log('Inserted User with id', this.id); } @AfterUpdate() logUpdate() { console.log('Updated User with id', this.id); } @AfterRemove() logRemove() { console.log('Removed User with id', this.id); } } ``` **AfterInsert、AfterRemove、AfterUpdate**此三個為Hooks 當User資料有變動時(insert、remove、update),則會在console.log出對應之訊息 **Hooks的觸發狀況** ![](https://hackmd.io/_uploads/ByJiGpdNn.png) ![](https://hackmd.io/_uploads/BJxRmauN2.png) 3. 在user.module.ts中引入相關套件及entity ``` // user.module.ts ... import { TypeOrmModule } from '@nestjs/typeorm'; import { UsersService } from './users.service'; import { User } from './user.entity'; ... @Module({ // This will create repository for us imports: [TypeOrmModule.forFeature([User])], ... ``` 4. 在app.module.ts中引入相關套件及entity ``` import { TypeOrmModule } from '@nestjs/typeorm'; ... import { User } from './users/user.entity'; import { Report } from './reports/report.entity'; ... @Module({ imports: [ TypeOrmModule.forRoot({ type: 'sqlite', database: 'db.sqlite', entities: [User, Report], synchronize: true, }), ... ... ``` [TypeORM Decorators Reference](https://orkhan.gitbook.io/typeorm/docs/decorator-reference) ### 請求送出的流程圖 ![](https://hackmd.io/_uploads/rJONzhOE2.png) ## 實例序列化 ![](https://hackmd.io/_uploads/B1kRDJtV3.png) 教案中使用的plainToClass函式現已改為使用plainToInstance