验证nestjs中的多层嵌套对象

validating multi-layers nested objects in nestjs

我正在尝试使用 classnestJs 中的验证器装饰器来验证以下类型的传入请求

{
    address: string
    location: { 
        longitude: string, 
        latitude : string
    }
}

。问题是它仅限于一层 nestedObject 。下面那个有效

class ProjectLocation { 
    @IsString()
    address: string; 
}

export class CreateProjectDto {

    @ValidateNested({each:true})
    @Type(()=>ProjectLocation)
    location:ProjectLocation
}

但是当另一个嵌套层被添加到 ProjectLocation 时,它不起作用,而且您不能在 ProjectLocation 中使用 @ValidatedNested 添加另一个 class 类型。

Error : No overload matches this call.

按我的预期工作,请考虑以下事项:

class SomeNestedObject {
    @IsString()
    someProp: string;
}

class ProjectLocation {
    @IsString()
    longitude: string;
    @IsString()
    latitude: string;
    @ValidateNested()
    @IsNotEmpty()
    @Type(() => SomeNestedObject)
    someNestedObject: SomeNestedObject;
}

export class CreateProjectDto {
    @IsString()
    address: string;
    @ValidateNested()
    @Type(() => ProjectLocation)
    location: ProjectLocation;
}

请注意,我在 someNestedObject 上使用 IsNotEmpty 来处理缺少道具的情况。


以下是经过正确验证的两个无效请求示例:

示例 1:

Request-Body:    
    {
        "address": "abc",
        "location": { 
            "longitude": "123",
            "latitude" : "456",
            "someNestedObject": {}
        }
    }

Response:
{
    "statusCode": 400,
    "message": [
        "location.someNestedObject.someProp should not be empty"
    ],
    "error": "Bad Request"
}

示例 2:

Request-Body:
{
    "address": "abc",
    "location": { 
        "longitude": "123",
        "latitude" : "456"
    }
}
Response:
{
    "statusCode": 400,
    "message": [
        "location.someNestedObject should not be empty"
    ],
    "error": "Bad Request"
}