Reputation: 63
When I send only one parameter, I got query result like string, not like string[]. This happened only from UI swagger, if I send from Postman - it works good.
I just want send from swagger-ui one parameter and got array of strings, not a single string.
How I can fix it? Help me please.
Example1: send one parameter and in my controller I got string like '25'
Example2: when I send 2 parameters in controller I can see array of strings ('25', '21')
export class List {
@ApiProperty({ isArray: true, type: String, required: false })
@IsOptional()
public categories?: string[];
}
Upvotes: 6
Views: 9358
Reputation: 1
I have the same problem with you.
I decide to create a utils transform called toArray.
Code:
export function ToArray(): (target: any, key: string) => void {
return Transform((params: TransformFnParams) => {
const { value } = params;
if (Array.isArray(value)) {
return value;
}
if (typeof value === 'string') {
return value.split(',').map(item => item.trim());
}
return [];
});
}
So when i need to transform i just need import ToArray any where need to transform to Array.
@ApiProperty({ description: 'List of category IDs', example: ['47b32970-4997-4364-91b6-4b5533941307', '620b7c84-6d63-492e-8abb-7606e04a375c'], required: false })
@ToArray()
@IsArray()
categories?: string[];
Upvotes: 0
Reputation: 76
when you fill a single category the query param will be translated as a string while when you fill in several categories understand it as a array.
to solve this problem I added in DTO :
@Transform(({ value }) => (Array.isArray(value) ? value : Array(value)))
I force the cast to array
Upvotes: 6
Reputation: 81
You should try to spread your parameter in a const in services edit:
I don't know how to explain in formal words, but a array of strings of one item, for JAVASCRIPT, seems with the same thing as one string value.
Because array is not a type, but a form of a type....
So, if you, in your controller, before do anything with it, you redeclare as:
@Get(":id")
findManybyId(@Param("id") id: string[]) {
const idArray = [...id];
return await this.service.findManyById(idArray);
}
It will solve your problem about being an array
old answer:
You should try to change in your controller where you make your input decorator.
in your case, i don't know if you are using ID to get, but you must to do as the example:
@ApiOperation({
summary: "Get many categories by ID",
})
async getMany(
@Param("id") ids: string[],
) {
return await this.categoriesService.getMany(id);
}
Upvotes: 1