nestjs从零到一,快速上手(六)---- 增删改查以及管道(Pipe)的使用

1. 批量更新数据以及关联数据

user.controller.ts

  @Patch('/update')
  updateUser(@Body() dto: any) {
    const user = dto as User;
    return this.userService.update(user);
  }

user.service.ts

  async update(body) {
    if (!body.id) {
      return 'id不能为空';
    }
    // 更新多个模型数据
    const userTemp: any = await this.findProfile(body.id);
    const newUser = this.user.merge(userTemp, body); // 合并数据
    return this.user.save(newUser);
    // return this.user.update(query.id, query); // 更新单个模型
  }
  findProfile(id: number) {
    return this.user.findOne({
      where: {
        id,
      },
      relations: { profile: true },
    });
  }

注意:  @OneToOne(() => Profile, (profile) => profile.user, { cascade: true }) // cascade:设置cascade为true 子数据也自动插入数据库

2. 全局管道Pipe

pnpm i --save class-validator class-transformer
2.1 main.ts引入  

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

app.useGlobalPipes(new ValidationPipe());

2.2 使用

创建dto.ts

import { IsNotEmpty, IsString, Length } from 'class-validator';

export class SignUserDto {
  @IsString()
  @IsNotEmpty()
  @Length(6, 20)
  username: string;

  @IsString()
  @IsNotEmpty()
  @Length(6, 20)
  password: string;
}

使用:auth.controller.ts

import {
  Body,
  Controller,
  Post,
  UseFilters,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { TypeormFilter } from 'src/filters/typeorm.filter';
import { SignUserDto } from './dto/sign-user.dto';

@Controller('auth')
@UseFilters(new TypeormFilter())
export class AuthController {
  constructor(private authService: AuthService) {}
  @Post('signin')
  signin(@Body() body: SignUserDto) {
    const { username } = body;

    return this.authService.signin(username);
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值