summaryrefslogtreecommitdiff
path: root/src/pages/api/shop/preferredBrand.js
blob: 4cb35c84d2b6eb6b8e2c58be9b66d966ecd525f4 (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import axios from 'axios';
import { createClient } from 'redis';

const SOLR_HOST = process.env.SOLR_HOST;
const client = createClient();

client.on('error', (err) => console.error('Redis Client Error', err));

const connectRedis = async () => {
  if (!client.isOpen) {
    await client.connect();
  }
};

export default async function handler(req, res) {
  await connectRedis();

  try {
    let params = '*:*';
    let sort =
      'sort=if(exists(sequence_i),0,1) asc,sequence_i asc, if(exists(image_s),0,1) asc ';
    let rows = 20;

    if (req.query.params) {
      rows = 20;
      switch (req.query.params) {
        case 'level_s':
          params = 'level_s:prioritas';
          break;
        case 'search':
          params = `name_s:"${req.query.q.toLowerCase()}"`;
          sort = '';
          rows = 1;
          break;
        default:
          params = `name_s:${req.query.params}`.toLowerCase();
      }
    }
    if (req.query.rows) rows = req.query.rows;

    const url = `${SOLR_HOST}/solr/brands/select?q=${params}&q.op=OR&indent=true&rows=${rows}&${sort}`;
    const brands = await axios(url);
    const dataBrands = responseMap(brands.data.response.docs);

    res.status(200).json(dataBrands);
  } catch (error) {
    console.error('Error fetching data from Solr:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

const responseMap = (brands) => {
  return brands.map((brand) => {
    return {
      id: brand.id,
      name: brand.display_name_s,
      logo: brand.image_s || '',
      sequence: brand.sequence_i || '',
    };
  });
};