Vue3 + Nest 实现博客管理系统 后端篇(六):博客的增删改查

386 阅读1分钟

博客的创建

nest g res blog

同样的是RESTAPI风格,生成crud,添加entity

image.png

import { Base } from 'libs/Entities/base.entity';
import { Tag } from 'src/tag/entities/tag.entity';
import { Column, Entity, ManyToOne } from 'typeorm';

@Entity()
export class Blog extends Base {
  @Column({
    nullable: true,
    comment: '博客标题',
  })
  title: string;

  @Column({
    comment: '封面',
  })
  cover: string;

  @Column({
    comment: '介绍',
  })
  introduce: string;

  @Column({
    comment: '内容',
    nullable: true,
  })
  content: string;

  @Column({
    comment: '内容HTML',
    nullable: true,
  })
  htmlconten: string;

  @ManyToOne(() => Tag)
  tag: Tag;

  @Column({
    nullable: true,
  })
  state: boolean;
}

image.png

然后重启,就会生成blog表,接下来开始写博客创建的接口

image.png

image.png

  Apiresult = new ApiresultService();

  constructor(
    @InjectRepository(Blog) private blogRepository: Repository<Blog>,
  ) {}

  async create(createBlogDto) {
    const result = await this.blogRepository.save(createBlogDto);
    if (result) {
      return this.Apiresult.MESSAGE(200, '插入成功');
    } else {
      return this.Apiresult.MESSAGE(500, '插入失败,请检查是参数');
    }
  }

接下来测试一下

image.png

博客的查询

image.png

image.png

image.png


interface SearchType {
  // 搜索条件
  search: any;
  pageNo: number;
  pageSize: number;
}
  async search(body: SearchType) {
    const { pageNo, pageSize, search } = body;
    const skipCount = (pageNo - 1) * pageSize; // 分页查询,计算要跳过的条数

    const [list, total] = await this.blogRepository
      .createQueryBuilder('entity') // 设置表别名
      .where(search || {}) // 设置查询条件
      .skip(skipCount)
      .take(pageSize)
      .getManyAndCount();
    return {
      ...this.Apiresult.MESSAGE(200, '查询成功', list),
      total,
    };
  }

然后我们调试一下

image.png

目前所有的请求都加上的token验证,所以在调试的时候也需要加上

image.png

然后加上条件查询

image.png 都没有问题,这里我们没有做模糊查询,可以借鉴上一节查询标签的模糊查询

博客的删除

image.png

image.png

  async delete(id) {
    if (!id) return this.Apiresult.MESSAGE(500, '缺少id');
    const data = await this.blogRepository.delete(id);

    if (data.affected > 0) {
      return this.Apiresult.MESSAGE(200, '删除成功');
    }
    return this.Apiresult.MESSAGE(500, '删除失败, 请检查入参');
  }

我们接着测试一下

image.png

image.png 数据库里已经没有了id为1的数据

博客修改

image.png

image.png

  async update(body) {
    const data = await this.blogRepository.update(body.id, body);
    if (data.affected > 0) {
      return this.Apiresult.MESSAGE(200, '修改成功');
    }
    return this.Apiresult.MESSAGE(500, '修改失败, 请检查入参');
  }

测试一下

image.png

image.png 没有问题