- Nest.js学习之路(16)-typeorm(3)basic
- Nest.js学习之路(14)- TypeORM库(1)存取 i
- Nest.js学习之路(19)-TypeORM(6)Query
- Nest.js学习之路(23)-TypeORM(10) Embe
- Nest.js学习之路(22)-TypeORM(9) Relat
- Nest.js学习之路(21)-TypeORM(8) Relat
- Nest.js学习之路(20)-TypeORM(7)Query
- 在 Nest.js 中使用 MongoDB 与 TypeORM
- Nest.js学习之路(15)-typeorm(2)新增数据
- Nest.js学习之路(1)-开发环境准备
这章继续完成CRUD部分
语法相当简洁
platform.service.ts新增相关方法
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Platform } from 'shared/entity/Platform';
import { Repository } from 'typeorm';
import { PlatformDTO } from 'app.controller';
@Injectable()
export class PlatformService {
constructor(
@InjectRepository(Platform)
private readonly platformRepo: Repository<Platform>,
){}
async addPlatform(data: PlatformDTO){
const platformData = new Platform();
platformData.platformname = data.platformname;
platformData.url = data.url;
platformData.title = data.title;
return await this.platformRepo.save(platformData);
}
async getPlatforms(): Promise<Platform []> {
return await this.platformRepo.find(); // find 沒传入参数代表获取全部资料
}
async getPlatformById(id): Promise<Platform> {
return await this.platformRepo.findOne(id); // 以id搜寻,沒找到return null
// return await this.platformRepo.findOneOrFail(id); // 以id搜寻,沒找到会丟出例外
}
async updatePlatform(id, data: PlatformDTO) {
return await this.platformRepo.update(id, data); // 用data里的值更新到资料库
}
async deletePlatform(id) {
return this.platformRepo.delete(id); // delete只需要传入id
}
}
更新platform.controller.ts
import { Controller, Post, Body, Get, Query, UnauthorizedException, Param, Put, Delete } from '@nestjs/common';
import { PlatformDTO } from 'app.controller';
import { PlatformService } from './platform.service';
@Controller('platform')
export class PlatformController {
constructor(private readonly platformService: PlatformService) {}
@Get()
platformList() {
return this.platformService.getPlatforms();
}
@Get('platforms')
queryedList(@Query() query){
throw new UnauthorizedException('请登入');
return query;
}
@Get(':platformId')
getPlatformById(@Param('platformId') id){
return this.platformService.getPlatformById(id);
}
@Put(':platformId')
updateUserById(@Param('platformId') id, @Body() platformDTO: PlatformDTO){
return this.platformService.updatePlatform(id, platformDTO);
}
@Delete(':platformId')
delete(@Param('platformId') id){
return this.platformService.deletePlatform(id);
}
@Post()
create(@Body() platformDTO: PlatformDTO){
// throw new HttpException('糟糕!您的要求有问题,请联系管理员', HttpStatus.BAD_REQUEST);
return this.platformService.addPlatform(platformDTO);
}
}
用postman测试
GET localhost:3000/platform

GET localhost:3000/platform/2

DELETE localhost:3000/platform/1

PUT localhost:3000/platform/2

GET localhost:3000/platform

推荐一下我的公众号: 【 geekjc 】,微信号: 【 c8706288 】一起学习交流编程知识,分享经验,各种有趣的事。

网友评论