Search code examples
strapiqs

How to filter dynamically in strapi with qs


I need to create a simple filter on strapi together with qs.

All these parameters are optional and are added by clicking on the checkbox.

The problem is that I can't make a filter based on an array, I use $in to match the values from the incoming array with the server and get an error

enter image description here

export interface responseFilterType {
    type_product?: [string]
    user_type?: [string]
    weight?: string | number
}

enter image description here

qs.stringify({
        populate: "*",
        filters: {
            $and: [
                {
                    ...(value.type_product && {
                        type_product: {
                            $in: value.type_product,
                        }
                    })
                },
                {
                    ...(value.user_type && {
                        user_type: {
                            $in: value.user_type,
                        }
                    })
                }
            ] ,

        },
    }, {
        encodeValuesOnly: true, // prettify URL
    });
data from server

enter image description here

Main type

enter image description here

type_product & user_type

enter image description here


Solution

  • That's what I got, thanks @antokhio

    qs.stringify({
            filters: {
                $and: [
                    {
                        weight: {
                            ...(value.weight&&typeof value.weight === "string" && {
                                    $between: [15, 30],
                            }),
                            ...(value.weight&&typeof value.weight === "number"&& value.weight<=15 && {
    
                                $lt: value.weight,
    
                            }),
                            ...(value.weight&&typeof value.weight === "number"&& value.weight>=30 && {
                                $gt: value.weight,
                            }),
                        }
                    },
                    {
                        type_product: {
                            Title: {$in: value.type_product}
    
                        }
    
                    },
                    {
                        user_type: {
                            Title: {$in: value.user_type}
                        }
    
                    }
                ],
    
            },
        }, {
            encodeValuesOnly: true, // prettify URL
        });