How to filter dynamically in strapi

Viewed 2042

This might be the noobiest Strapi or possibly backend question at all, but I have just started doing backend, so please bear with me.

That being said, I have the following case. I am building an online shop and every product I have has a price (a required field) and new_price (optional). When I filter my API by min-max value, I would like to filter price if new_price is not available and new_price if it is available. Is this possible at all in strapi?

{
  id: 2,
  attributes: {
  name: "My name",
  createdAt: "2022-01-15T11:28:46.138Z",
  updatedAt: "2022-02-16T10:38:20.412Z",
  publishedAt: "2022-01-15T11:29:30.306Z",
  description: "Lorem ipsum",
  item_code: "688002",
  slug: "some-slug-here",
  available: true,
  price: 59,
  new_price: 21.9
}
http://localhost:1337/api/products?filters[price || new_price][$gte]=50
2 Answers

You're answer is perfectly fine. Just posted my full implementation here so that it may help others who stumble upon it.

const qs = require("qs");
const query = qs.stringify(
  {
    filters: {
      $or: [
        {
          $and: [
            { new_price: { $notNull: true } },
            { new_price: { $gte: minPrice } },
            { new_price: { $lte: maxPrice } },
          ],
        },
        {
          $and: [
            { new_price: { $null: true } },
            { price: { $gte: minPrice } },
            { price: { $lte: maxPrice } },
          ],
        },
      ],
    },
  },
  {
    encodeValuesOnly: true,
  }
);

await request(`/api/books?${query}`);

So I came up with this solution. It might be ugly and not how it's done, but it works, and I couldn't think of anything else. If somebody has a better solution, I will greatly appreciate it!

const query = qs.stringify(
    {
      populate: '*',
      pagination: {
        page: page,
        pageSize: PER_PAGE
      },
      filters: {
        $or: [
          {
            $and: [
              [
                {
                  new_price: {
                    $null: true
                  }
                },
                {
                  price: {
                    $gte: minPrice
                  }
                },
                {
                  price: {
                    $lte: maxPrice
                  }
                }
              ]
            ]
          },
          {
            $and: [
              [
                {
                  new_price: {
                    $notNull: true
                  }
                },
                {
                  new_price: {
                    $gte: minPrice
                  }
                },
                {
                  new_price: {
                    $lte: maxPrice
                  }
                }
              ]
            ]
          }
        ]
      }
    },
Related