简体   繁体   中英

nestJS class-validator for complex data structure

I have an XML document that I have parsed into JSON. The element values have an odd structure.

{
"id": [
    "62314"
],
"artnr": [
    "OBS6680"
],
"categories": [
    {
        "category": [
            {
                "cat": [
                    {
                        "id": [
                            "153"
                        ],
                        "title": [
                            "Lingerie"
                        ]
                    },
                    {
                        "id": [
                            "184"
                        ],
                        "title": [
                            "Catsuits"
                        ]
                    }
                ]
            }
        ]
    }
]
}

The top-level elements I use

@IsArray()
@ArrayNotEmpty()
@IsString({ each: true })

I am unclear about how to add the categories element into the DTO.

Any pointers will be great.

Thanks

I usually go through each property when I know the data structure.

export class Cat {
    @IsArray()
    @ArrayNotEmpty()
    @IsString({ each: true })
    id: string;
    @IsArray()
    @ArrayNotEmpty()
    @IsString({ each: true })
    title: string;

}

export class CatExtra {
    @ValidateNested({ each: true })
    @Type(() => Cat)
    cat : Cat[]

}

export class Category {
 
    @ValidateNested({ each: true })
    @Type(() => CatExtra)
    category : CatExtra[]
}


export class Categories {
 
    @ValidateNested({ each: true })
    @Type(() => Category)
    categories : Category[]
}

in you main.ts, enable enableImplicitConversion so that nested properties gets valdiated

import { ValidationPipe } from '@nestjs/common';
app.useGlobalPipes(
    new ValidationPipe({
      transformOptions: {
        enableImplicitConversion: true, // allow conversion underneath
      },
    }),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM