Function overload
One implementation for many signatures.
Another approach would be to simply receive the categoriesIds
in the DTO.
@ArrayNotEmpty()
@ArrayUnique()
@IsCardinal({ each: true })
readonly categoriesIds: number[];
After that, we could transform them to the objects mentioned in the previous solution. For better encapsulation, in the file common/util/id.util, create the function wrapId()
. We'll use a function overload to have just a single implementation, preventing the need to write two separate functions depending on the parameter (one or many ids). The tooltip adapts depending on the input provided.
export function wrapId(id: number): IdDto;
export function wrapId(ids: number[]): IdDto[];
export function wrapId(idOrIds: number | number[]) {
if (Array.isArray(idOrIds)) {
const ids = idOrIds;
return ids.map((id) => ({ id }));
}
const id = idOrIds;
return { id };
}
What remains to be done is to, in the ProductsService
, wrap the ids and use them.
create(createProductDto: CreateProductDto) {
const { categoriesIds } = createProductDto;
const categories = wrapId(categoriesIds);
const product = this.productsRepository.create({
...createProductDto,
categories,
});
return this.productsRepository.save(product);
}
Commit - Function overload for wrapping ids
Last updated