summaryrefslogtreecommitdiff
path: root/src/pages/api/flashsale-header.js
blob: 916a9cd24faeefe2b311a13d2d0c5a6983f3370e (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
import odooApi from '@/core/api/odooApi';
import { createClient } from 'redis';

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) {
  try {
    await connectRedis();
    const cacheKey = `flashsale_header`;

    // Cek data yang ada di Redis
    let cachedData = await client.get(cacheKey);

    if (cachedData) {
      const data = JSON.parse(cachedData);

      // Periksa apakah data adalah array dan panjangnya 0
      if (!data || (Array.isArray(data) && data.length === 0)) {
        await client.del(cacheKey); // Hapus kunci jika data kosong
        return res.status(200).json({ data: [] });
      }
      // Periksa apakah end_date lebih besar dari waktu saat ini
      const currentTime = new Date();
      if (data[0].endDate && new Date(data[0].endDate) < currentTime) {
        await client.del(cacheKey); // Hapus kunci jika end_date lebih kecil dari waktu saat ini
        return res.status(200).json({ data: [] });
      }
      return res.status(200).json({ data });
    } else {
      const flashSale = await odooApi('GET', `/api/v1/flashsale/header?is_show_program=true`);
      if (flashSale.length === 0) {
        return res.status(200).json({ data: [] });
      } else {
        await client.set(
          cacheKey,
          JSON.stringify(flashSale),
          'EX',
          flashSale.duration
        );

        cachedData = await client.get(cacheKey);
        const data = JSON.parse(cachedData);
        return res.status(200).json({ data });
      }
    }
  } catch (error) {
    console.error('Error interacting with Redis or fetching data:', error);
    return res.status(500).json({ error: 'Internal Server Error' });
  }
}