Commit 048e6e11 by Ravindra Kanojiya

updated redis

1 parent 7584bb4b
import Redis from "ioredis";
const redis = new Redis({
host: process.env.REDIS_HOST || "127.0.0.1",
port: process.env.REDIS_PORT || 6379,
password: process.env.REDIS_PASSWORD || undefined,
});
export default redis;
\ No newline at end of file
......@@ -29,6 +29,7 @@
"react-paginate": "^8.2.0",
"react-redux": "^9.1.2",
"swiper": "^11.2.6",
"yup": "^1.7.1"
"yup": "^1.7.1",
"ioredis": "^5.6.1"
}
}
import redis from "@/lib/redis";
export default async function handler(req, res) {
if (req.method !== "DELETE") {
return res.status(405).json({ error: "Method not allowed" });
}
try {
// ⚠️ Dangerous: deletes all keys
await redis.flushall();
return res.status(200).json({
success: true,
message: "All Redis keys deleted",
});
} catch (error) {
return res.status(500).json({
success: false,
error: error.message,
});
}
}
\ No newline at end of file
......@@ -10,6 +10,7 @@ import BlogHome from "@/container/Home/BlogHome";
import Catalogues from "@/container/Home/Catalogues";
import { getCataloguesBySlug } from "@/services/cataloguesApi";
import { getHomeSlug } from "@/services/homeApi";
import { getRedisClient } from "@/redis-client";
const Home = ({ homepage, cataloguesData={cataloguesData}, homeData }) => {
......@@ -36,10 +37,31 @@ const Home = ({ homepage, cataloguesData={cataloguesData}, homeData }) => {
export default Home;
/* ---------- SSR ---------- */
export async function getServerSideProps({ params }) {
const redis = getRedisClient();
// Redis key and expiry
const REDIS_KEY = `${process.env.REDIS_KEY_PREFIX}_homepage`;
const REDIS_KEY_CATALOGUES = `${process.env.REDIS_KEY_PREFIX}_catalogues`;
const REDIS_EXPIRE = parseInt(process.env.REDIS_KEY_EXPIRE) || 86400; // default: 24 hrs
try {
const cachedData = await redis.get(REDIS_KEY);
const cachedCataloguesData = await redis.get(REDIS_KEY_CATALOGUES);
if (cachedData && cachedCataloguesData) {
console.log('redis data fetched');
return {
props: {
cataloguesData: JSON.parse(cachedCataloguesData),
homeData: JSON.parse(cachedData),
},
}};
const cataloguesData = await getCataloguesBySlug();
const homeData = await getHomeSlug();
await redis.set(REDIS_KEY, JSON.stringify(homeData), "EX", REDIS_EXPIRE);
await redis.set(REDIS_KEY_CATALOGUES, JSON.stringify(cataloguesData), "EX", REDIS_EXPIRE);
console.log('normal data fetched');
return {
props: {
cataloguesData,
......
import Redis from "ioredis";
let redis;
if (process.env.REDIS_URL) {
redis = new Redis(process.env.REDIS_URL);
}
export const getRedisClient = () => {
if (!redis) {
redis = new Redis(process.env.REDIS_URL);
}
return redis;
};
\ No newline at end of file
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!