blob: 4e62c3292892d4b6ef051a94909573fefdec5979 (
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
62
63
64
65
66
|
import odooApi from '@/core/api/odooApi';
import { createClient } from 'redis';
import _ from 'lodash-contrib';
import axios from 'axios';
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) {
const { query, operation, duration } = req.query;
res.setHeader('Cache-Control', 'no-store');
try {
await connectRedis();
const cacheKey = `flashsale_product:${operation}:${query}`;
let cachedData = await client.get(cacheKey);
if (cachedData) {
const data = JSON.parse(cachedData);
if (!data || (Array.isArray(data) && data.length === 0)) {
await client.del(cacheKey)
return res.status(200).json({ data: [] });
}
return res.status(200).json({ data });
} else {
const dataProductSearch = await axios(
`${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/search?${query}&operation=${operation}`
);
if (dataProductSearch.data.length === 0) {
return res.status(200).json({ data: [] });
} else {
const ttl = Math.max(1, parseInt(String(duration), 10) || 300);
await client.set(
cacheKey,
JSON.stringify(dataProductSearch.data),
'EX',
tt
);
cachedData = await client.get(cacheKey);
return res.status(200).json({ data: JSON.parse(cachedData) });
}
}
} catch (error) {
console.error('Error interacting with Redis or fetching data:', error);
return res.status(500).json({ error: 'Internal Server Error' });
}
}
|