summaryrefslogtreecommitdiff
path: root/src/pages/api/page-content.js
blob: a6514505f7bdf57e183da2d04d8c72d548d201aa (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
import { createClient } from 'redis';
import { getPageContent } from '~/services/pageContent';
// import { fetchCategoryManagementSolr } from '../../lib/home/api/categoryManagementApi';
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 { path } = req.query;
  try {
    await connectRedis();
    // await client.del('onbording-popup');

    let cachedData;
    if (req.method === 'GET') {
      cachedData = await client.get(`page-content:${path}`);

      if (!cachedData) {
        const items = await getPageContent({ path });
        await client.set(
          `page-content:${path}`,
          JSON.stringify(items),
          'EX',
          604800 // Expiry 1 minggu
        );
        cachedData = await client.get(`page-content:${path}`);
      }
      const data = cachedData ? JSON.parse(cachedData) : null;
      res.status(200).json({ data });
    } else {
      res.setHeader('Allow', ['GET']);
      res.status(405).end(`Method ${req.method} Not Allowed`);
    }
  } catch (error) {
    console.error('Error interacting with Redis:', error);
    res.status(500).json({ error: 'Error interacting with Redis' });
  }
}