diff options
| author | Miqdad <ahmadmiqdad27@gmail.com> | 2025-10-06 22:06:41 +0700 |
|---|---|---|
| committer | Miqdad <ahmadmiqdad27@gmail.com> | 2025-10-06 22:06:41 +0700 |
| commit | 9b567f03de8213cb96d000256e3bd151282b98d8 (patch) | |
| tree | ad816186026d2d2fbd5075365eccda94c32bf6e1 /src | |
| parent | 0c8f06679b1f6ba3f6c8a73fecf461646b842a38 (diff) | |
<Miqdad> try fix caching flash sale
Diffstat (limited to 'src')
| -rw-r--r-- | src/pages/api/search-flashsale.js | 27 |
1 files changed, 20 insertions, 7 deletions
diff --git a/src/pages/api/search-flashsale.js b/src/pages/api/search-flashsale.js index c00f6c64..4e62c329 100644 --- a/src/pages/api/search-flashsale.js +++ b/src/pages/api/search-flashsale.js @@ -15,35 +15,48 @@ const connectRedis = async () => { 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`; - // await client.del(cacheKey); + + + const cacheKey = `flashsale_product:${operation}:${query}`; + + 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 + 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}]` + `${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', - duration + tt ); cachedData = await client.get(cacheKey); - return res.status(200).json({ data: cachedData }); + + + return res.status(200).json({ data: JSON.parse(cachedData) }); } } } catch (error) { |
