nest create和findone实现

99 阅读1分钟

一些修改

做了一些修改

import { Module } from '@nestjs/common';

import { database } from './config';
import { ContentModule } from './modules/content/content.module';
import { CoreModule } from './modules/core/core.module';
import { DatabaseModule } from './modules/database/database.module';
import { PersonModule } from './modules/person/person.module';

@Module({
    imports: [PersonModule, ContentModule, CoreModule.forRoot(), DatabaseModule.forRoot(database)],
    controllers: [],
    providers: [],
})
export class AppModule {}

PersonController PersonService 删除了 只要imports中有personModule就可以被访问到

编写entity controller service

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class PersonEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ default: '' })
    name: string;

    @Column()
    age: number;
}
@Post()
    create(@Body() person: Partial<PersonEntity>) {
        console.log('创建person');
        return `received: ${JSON.stringify(person)}`;
    }
// create(createPersonDto: CreatePersonDto) {}
    async create(person: Partial<PersonEntity>): Promise<PersonEntity> {
        const { name } = person;
        if (!name) {
            throw new HttpException('缺少文章标题', 401);
        }
        const doc = await this.personRepository.findOne({ where: { name } });
        if (doc) {
            throw new HttpException('文章已存在', 401);
        }
        return this.personRepository.save(person);
    }

apifox 调接口 参数是json形式

一开始async 和 await 我删掉了 导致doc那边的验证一直卡着

image.png

会接收到promise对象 一直判定为真

image.png

成功写入数据库

findAll

测试了下findAll 有以下问题

getRepository已经弃用了 第二个findAll还需要用到分页相关的东西

export interface PostsRo { list: PostsEntity[]; count: number; }

还多了这个玩意 我不知道怎么理解

throw new HttpException(`id为${id}的文章不存在`, 401);

这中形式后期应该改成DTO的形式去做校验

findbyid 也被废弃了

async findOne(id: number): Promise<PersonEntity> {
        return this.personRepository.findOne({ where: { id } });
    }

需要这种形式

其他方法都能看懂就不测试了

import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getRepository, Repository } from 'typeorm';
import { PostsEntity } from './posts.entity';

export interface PostsRo {
  list: PostsEntity[];
  count: number;
}
@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsEntity)
    private readonly postsRepository: Repository<PostsEntity>,
  ) {}

  // 创建文章
  async create(post: Partial<PostsEntity>): Promise<PostsEntity> {
    const { title } = post;
    if (!title) {
      throw new HttpException('缺少文章标题', 401);
    }
    const doc = await this.postsRepository.findOne({ where: { title } });
    if (doc) {
      throw new HttpException('文章已存在', 401);
    }
    return await this.postsRepository.save(post);
  }
  
  // 获取文章列表
  async findAll(query): Promise<PostsRo> {
    const qb = await getRepository(PostsEntity).createQueryBuilder('post');
    qb.where('1 = 1');
    qb.orderBy('post.create_time', 'DESC');

    const count = await qb.getCount();
    const { pageNum = 1, pageSize = 10, ...params } = query;
    qb.limit(pageSize);
    qb.offset(pageSize * (pageNum - 1));

    const posts = await qb.getMany();
    return { list: posts, count: count };
  }

  // 获取指定文章
  async findById(id): Promise<PostsEntity> {
    return await this.postsRepository.findOne(id);
  }

  // 更新文章
  async updateById(id, post): Promise<PostsEntity> {
    const existPost = await this.postsRepository.findOne(id);
    if (!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    const updatePost = this.postsRepository.merge(existPost, post);
    return this.postsRepository.save(updatePost);
  }

  // 刪除文章
  async remove(id) {
    const existPost = await this.postsRepository.findOne(id);
    if (!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    return await this.postsRepository.remove(existPost);
  }
}