nestjsx/crud + TypeORM:补丁和 post 导致空请求

nestjsx/crud + TypeORM: patch and post results in empty request

我试图通过使用 TypeORM 和 crud 库创建一个简单的 REST Api 来进入 nestjs。到目前为止,我已经创建了一个基于工作角色的身份验证,但我 运行 遇到了一个奇怪的问题。我使用 crud 库为用户实体创建了一个简单的控制器。 GET 请求工作正常,没有任何问题。但是我不能 POST 创建新用户,也不能使用 PATCH 更新用户。我认为这可能只是我犯的一个非常愚蠢的错误,但由于我没有编写太多代码,所以我找不到与文档中示例的任何差异。

当我尝试修补 属性 时,它只是用原始用户对象响应我,没有进行任何更改(就像我发送了一个空请求)。 当我尝试 post 新用户时,响应是以下错误消息:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Empty data. Nothing to save."
}

可能与验证有关..

这是我的用户控制器:

import { Controller, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
import { AuthGuard } from '@nestjs/passport';
import { ApiTags, ApiSecurity } from '@nestjs/swagger';
import { RolesGuard } from 'src/auth/role.guard';
import { Roles } from './roles.decorator';
import { Crud, CrudController } from '@nestjsx/crud';

@UseGuards(AuthGuard('jwt'), RolesGuard)
@Crud({
    model: {
        type: User
    },
    routes: {
        exclude: ['createManyBase', 'replaceOneBase'],
    },
    //validation: false,
})
@Roles('admin')
@ApiSecurity('bearer')
@ApiTags('user')
@Controller('user')
export class UserController implements CrudController<User> {
    constructor(public service: UserService) {}
}

这是我的用户服务:

import { Injectable, Body, NotFoundException } from '@nestjs/common';
import { CreateUserDTO } from './dto/create-user.dto';
import { User } from './user.entity';
import { GetUsersFilterDto } from './dto/get-users-filter.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRepository } from './user.repository';
import { Role } from './role.entity';
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';

@Injectable()
export class UserService extends TypeOrmCrudService<User> {
    constructor(
        @InjectRepository(User) user,
        private userRepository: UserRepository
    ) {
        super(user);
    }

    async getUserByName(username: string): Promise<User>{
        const found = await this.userRepository.findOne({
            where: {
                username: username,
            }, 
            relations: ["roles"] 
        });
        if (!found){
            throw new NotFoundException('User "${username}" not found!');
        }
        return found;
    }

    async getUserById(id: number): Promise<User>{
        const found = await this.userRepository.findOne(id, {relations: ["roles"] });
        if (!found){
            throw new NotFoundException('User with "${id}" not found');
        }
        return found;
    }



    async matchRoles(roles: string[], userroles: Role[]){
        let match = false;
        console.log(userroles)
        userroles.forEach(r => {
            if (roles.indexOf('r.name')){
                match = true;
            }
        })

        return match;
    }
}

这是实体:

import { Entity, Column, PrimaryGeneratedColumn, ManyToMany, JoinTable, BeforeInsert, Unique } from 'typeorm';
import { Role } from './role.entity';
import * as bcrypt from 'bcryptjs';
import { Exclude } from 'class-transformer';
import { ApiProperty } from '@nestjs/swagger';


@Entity('auth_user')
@Unique(['username'])
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @ApiProperty()
    @Column({ length: 30 })
    username: string;

    @ApiProperty()
    @Column()
    firstName: string;

    @ApiProperty()
    @Column()
    lastName: string;

    @ApiProperty()
    @Column()
    email: string;


    @BeforeInsert()
    async hashPassword() {
        this.password = await bcrypt.hash(this.password, 10);
    }
    @ApiProperty()
    @Column()//({select: false})
    @Exclude()
    password: string;

    @ApiProperty()
    @Column({ default: true })
    isActive: boolean;

    @ManyToMany(
        type => Role,
        role => role.users,
        { cascade: true },
    )
    @JoinTable()
    roles?: Role[];
}

感谢任何提示

事实证明,这是验证。 Crud 已经激活了验证,我在 main.ts:

中有这个
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true}));

所以它被验证了两次,不知何故导致请求中的主体为空。我删除了它,现在我可以 post/patch/put.