summaryrefslogtreecommitdiff
path: root/src/lib/product/api/productSearchApi.js
blob: 1a6ad36a9b2293eff9518c3fc7f93641affa0ca8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import _ from 'lodash-contrib';
import axios from 'axios';

const productSearchApi = async ({ query, operation = 'OR' }) => {
  // Use POST for large product ID arrays to avoid URL length limits
  // GET request URL limit is typically 2KB-8KB; switch to POST if query string is large
  const QUERY_SIZE_THRESHOLD = 2000; // Switch to POST if query > 2KB

  if (query.length > QUERY_SIZE_THRESHOLD) {
    console.log(
      `[productSearchApi] Large query (${query.length} chars), using POST`,
    );

    // Parse query string into object for POST body
    const params = new URLSearchParams(query);
    const bodyData = {
      ...Object.fromEntries(params),
      operation,
    };

    const dataProductSearch = await axios.post(
      `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/search`,
      bodyData,
      {
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    return dataProductSearch.data;
  }

  // Small query, use standard GET request
  const dataProductSearch = await axios(
    `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/search?${query}&operation=${operation}`,
  );
  return dataProductSearch.data;
};

export default productSearchApi;