「文件」nestjs使用Typeorm实现数据库CRUD操作( 三 )
}
4.创建数据库增删读写API文件
在根目录下新建cat文件夹 , 并依次创建下列文件 。
4.1 cat.controller.ts
import { Body, Controller, Delete, Get, Inject, Param, Post, Put } from '@nestjs/common';
import { Result } from 'common/result.interface';
import { Cat } from './cat.entity';
import { CatService } from './cat.service';
@Controller('cat')
export class CatController {
constructor(
@Inject(CatService) private readonly CatService: CatService,
) { }
@Post()
async createCat(@Body() Cat: Cat): Promise {
await this.CatService.createCat(Cat);
return { code: 200, message: '创建成功' };
}
@Delete(':id')
async deleteCat(@Param('id') id: number): Promise {
await this.CatService.deleteCat(id);
return { code: 200, message: '删除成功' };
}
@Put(':id')
async updateCat(@Param('id') id: number, @Body() Cat: Cat): Promise {
await this.CatService.updateCat(id, Cat);
return { code: 200, message: '更新成功' };
}
@Get(':id')
async findOneCat(@Param('id') id: number): Promise {
const data = http://www.sos110.com/show/12/102670/await this.CatService.findOneCat(id);
return { code: 200, message: '查询成功', data };
}
}
4.2 cat.service.ts文件
import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cat } from './cat.entity';
@Injectable()
export class CatService {
constructor(
@InjectRepository(Cat) private readonly catRepo: Repository , // 使用泛型注入对应类型的存储库实例
) { }
/**
* 创建
*
* @param cat Cat 实体对象
*/
async createCat(cat: Cat): Promise {
/**
* 创建新的实体实例 , 并将此对象的所有实体属性复制到新实体中 。请注意 , 它仅复制实体模型中存在的属性 。
*/
// this.catRepo.create(cat);
// 插入数据时 , 删除 id , 以避免请求体内传入 id
delete cat.id;
return this.catRepo.save(cat);
/**
* 将给定实体插入数据库 。与save方法不同 , 执行原始操作时不包括级联 , 关系和其他操作 。
* 执行快速有效的INSERT操作 。不检查数据库中是否存在实体 , 因此如果插入重复实体 , 本次操作将失败 。
*/
// await this.catRepo.insert(cat);
}
/**
* 删除
*
* @param id ID
*/
async deleteCat(id: number): Promise {
await this.findOneById(id);
this.catRepo.delete(id);
}
/**
* 更新
*
* @param id ID
* @param cat Cat 实体对象
*/
async updateCat(id: number, cat: Cat): Promise {
await this.findOneById(id);
// 更新数据时 , 删除 id , 以避免请求体内传入 id
delete cat.id;
this.catRepo.update(id, cat);
}
/**
* 根据ID查询
*
* @param id ID
*/
async findOneCat(id: number): Promise {
return this.findOneById(id);
}
/**
* 根据ID查询单个信息 , 如果不存在则抛出404异常
* @param id ID
*/
private async findOneById(id: number): Promise {
推荐阅读
- 潍坊晚报|手机使用四年,凌晨自燃吓坏一家人
- 互联网的一些事|QuestMobile:2020 移动互联网人均使用时长同比增长 12.9%
- |为什么使用B+Tree?
- 驱动之家|专利文件曝光华为正开发屏下摄像头手机:正面都是屏
- cnBeta|专利文件暗示华为正在开发屏下隐藏式前摄智能机
- 山东伟豪思|袋料全自动拆垛机器人的使用给企业带来了哪些益处
- 融资微信否认监听用户聊天记录;苹果将投3.3亿美元在台建厂;小鹏汽车秘密提交IPO文件
- 网易网易披露招股文件:过去20年整体年化回报高达26.2%
- 无敌马克兔|使用3个看似简单的挑战,提高摄影技巧,拍摄出不俗的作品
- 摄影小强|存储先行者,光威SSD固态硬盘使用中的小惊喜
