I was trying to do a "multiple filter" in TS, So…
If i send nothing -> it returns all products normally;
But if i send some params -> it returns products filtered by the params.
(I used colors just for the example)
async load(params: params): LoadProducts.Result => {
const products = [];
if (params) {
if (params.red != undefined) // products.push( ...load.redProducts() );
if (params.blue != undefined) // products.push( ...load.blueProducts() );
if (params.green != undefined) // products.push( ...load.greenProducts() );
if (params.yellow != undefined) // products.push( ...load.yellowProducts() );
} else {
// products.push( ...load.products() );
}
return products;
}
Type of request:
type params = {
filter?: {
red?: boolean;
blue?: boolean;
green?: boolean;
yellow?: boolean;
};
};
Example of request:
{
"filter": {
"red": true,
"blue": true
}
}
How can I deal with the multiple IFs to verify the params, because each has its own function to load and I want to add more filters.
>Solution :
You have not included a minimal, reproducible example, but based on what you have shown, you can use a (map-like) array of tuples and iterate over it:
const colorFns = [
['red', load.redProducts.bind(load)],
['blue', load.blueProducts.bind(load)],
// etc...
] as const;
async load(params: params): LoadProducts.Result => {
const products = [];
if (params) {
for (const [color, fn] of colorFns) {
if (params[color] != undefined) products.push(...fn());
}
} else {
// products.push( ...load.products() );
}
return products;
}