iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 16
0
Modern Web

讀官網文件邊走邊學nest.js系列 第 16

Day16-TypeORM(三) basic CRUD

  • 分享至 

  • xImage
  •  

昨天使用TypeORM Repository API完成新增使用者

本來關於typeorm的設定放在根目錄底下的ormconfig.json,先搬到forRoot(),管理entity class比較方便
另外把共用的部份抽到另外抽到shared module底下

shard.module.ts

import { AuthGuard } from './guards/auth.guard';
import { HttpExceptionFilter } from './filters/httpexception.filter';
import { Module } from '@nestjs/common';
import { TransformResInterceptor } from './interceptors/transformRes.interceptor';
import {TypeOrmModule} from '@nestjs/typeorm';
import { UserDTOValidationPipe } from './pipes/userDTOValidation.pipe';
import { userEntities } from './entity'; 
@Module({
    imports: [
        TypeOrmModule.forRoot(
        {
           type: "postgres",
           host: "localhost",
           port: 5432,
           username: "postgres",
           password: "root",
           database: "users",
           synchronize: true,
           logging: false,
           entities: [
             ...userEntities, //在entity目錄下新增index.ts,把相關的entity export陣列方便管理
           ],
           migrations: [
              "src/shared/migration/**/*.ts"
           ],
           subscribers: [
              "src/shared/subscriber/**/*.ts"
           ],
        },
        ),
    ],
    providers: [
        UserDTOValidationPipe,
        AuthGuard,
        HttpExceptionFilter,
        TransformResInterceptor,
    ],
    })
export class SharedModule {}

在app.module.ts import shared module即可用在app module 注入相關providers
app.module.ts

...
@Module({
  imports: [
    SharedModule, // import shared module
    TypeOrmModule.forFeature([User]), // forFeature告訴nest.js在typeorm要存取相關的entity
  ],
  controllers: [AppController],
  providers: [
    AppService,
  ],
})
export class AppModule implements NestModule{
  ...
}

今天繼續完成RUD部分

語法相當簡潔

app.service.ts新增相關方法

export class AppService {
  constructor(
    
    // @InjectConnection('userConnection')
    // private readonly userConn: Connection,
    // @InjectEntityManager('userConnection')
    // private readonly entitymanager: EntityManager,
    @InjectRepository(User)
    private readonly userRepo: Repository<User>,
  ){}
  

  async addUser(data: UserDTO): Promise<User>{
    const user = new User();
    user.username = data.username;
    user.email = data.email;

    return await this.userRepo.save(user); // 新增一筆user資料
  }
  
  async getUsers(): Promise<User[]>{
    return await this.userRepo.find(); // find 沒傳入物件代表撈全部資料
  }

 async getUserById(id): Promise<User>{
    return await this.userRepo.findOne(id); // 以id搜尋,沒找到return null
    // return await this.userRepo.findOneOrFail(id); // 以id搜尋,沒找到會丟出例外
  }

  async updateUser(id, data: UserDTO){

    return await this.userRepo.update(id, data); // 用data裡的值更新到資料庫
  }

  async deleteUser(id){
    return this.userRepo.delete(id); // delete只需要傳入id
  }
}

更新app.controller.ts

...
export class AppController {
  constructor(private appService: AppService){}
  
  ...
  
  @Get()
  userList(){
    return this.appService.getUsers();
  }

  @Get('users')
  queryedList(@Query() query){
    throw new UnauthorizedException('請登入');
    return query;
  }
  
  @Get(':userId')
  getUserById(@Param('userId') id){
    return this.appService.getUserById(id);
  }

  @Put(':userId')
  updateUserById(@Param('userId') id, @Body() userDTO: UserDTO){
    return this.appService.updateUser(id, userDTO);
  }

  @Delete(':userId')
  delete(@Param('userId') id){
    return this.appService.deleteUser(id);
  }

使用postman測試
GET localhost:3000

GET localhost:3000/2

DELETE localhost:3000/1

PUT localhost:3000/2

GET localhost:3000

Github source code


上一篇
Day15-TypeORM(二)-新增資料
下一篇
Day17-TypeORM(四)設定一對多/多對一
系列文
讀官網文件邊走邊學nest.js31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言