From 2021ab8b5cdb975c8a982fcd54cf45c01db796df Mon Sep 17 00:00:00 2001 From: tanish35 Date: Thu, 24 Oct 2024 22:31:34 +0530 Subject: [PATCH] Remove cache upon new post --- backend/src/controllers/postController.ts | 12 +++++++--- backend/src/lib/redis.ts | 28 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/backend/src/controllers/postController.ts b/backend/src/controllers/postController.ts index 7528edb..4b37646 100644 --- a/backend/src/controllers/postController.ts +++ b/backend/src/controllers/postController.ts @@ -4,7 +4,7 @@ import prisma from "../lib/prisma"; import Fuse from "fuse.js"; import sendMail from "../mail/sendMail"; import { htmlToText } from "html-to-text"; -import { setCachedData, getCachedData } from "../lib/redis"; +import { setCachedData, getCachedData, deleteCachedPosts } from "../lib/redis"; // @ts-ignore const searchPosts = asyncHandler(async (req: Request, res: Response) => { @@ -38,7 +38,7 @@ const searchPosts = asyncHandler(async (req: Request, res: Response) => { }, }); - const plainTextPosts = posts.map((post : any) => ({ + const plainTextPosts = posts.map((post: any) => ({ ...post, content: htmlToText(post.content, { wordwrap: false, @@ -124,7 +124,7 @@ const createPost = asyncHandler(async (req: Request, res: Response, next) => { college_id: collegeId, }, }); - + await deleteCachedPosts(collegeId); return res.status(201).json({ post }); }); @@ -286,6 +286,11 @@ const deletePost = asyncHandler(async (req: Request, res: Response) => { user_id: true, }, }, + College: { + select: { + college_id: true, + }, + }, }, where: { post_id: postId }, }); @@ -313,6 +318,7 @@ const deletePost = asyncHandler(async (req: Request, res: Response) => { where: { post_id: postId }, }); }); + await deleteCachedPosts(post.College.college_id); return res.status(200).json({ message: "Post and comments deleted" }); }); diff --git a/backend/src/lib/redis.ts b/backend/src/lib/redis.ts index 28f0c9f..955488a 100644 --- a/backend/src/lib/redis.ts +++ b/backend/src/lib/redis.ts @@ -36,4 +36,32 @@ export const disconnectRedis = async (): Promise => { } }; +export const deleteCachedPosts = async (collegeId: string): Promise => { + try { + const collegePattern = `posts:${collegeId}:page:*`; + const allPattern = `posts:all:page:*`; + const collegeStream = redis.scanStream({ match: collegePattern }); + const allStream = redis.scanStream({ match: allPattern }); + collegeStream.on("data", (keys) => { + if (keys.length) { + redis.del(...keys); + } + }); + allStream.on("data", (keys) => { + if (keys.length) { + redis.del(...keys); + } + }); + collegeStream.on("end", () => { + console.log(`Deleted cache for collegeId: ${collegeId}`); + }); + + allStream.on("end", () => { + console.log(`Deleted all cache entries.`); + }); + } catch (error) { + console.error("Error deleting cached posts from Redis", error); + } +}; + export default redis;