Skip to content

Commit

Permalink
Remove cache upon new post
Browse files Browse the repository at this point in the history
  • Loading branch information
tanish35 committed Oct 24, 2024
1 parent 5054883 commit 2021ab8
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
12 changes: 9 additions & 3 deletions backend/src/controllers/postController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 });
});

Expand Down Expand Up @@ -286,6 +286,11 @@ const deletePost = asyncHandler(async (req: Request, res: Response) => {
user_id: true,
},
},
College: {
select: {
college_id: true,
},
},
},
where: { post_id: postId },
});
Expand Down Expand Up @@ -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" });
});
Expand Down
28 changes: 28 additions & 0 deletions backend/src/lib/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,32 @@ export const disconnectRedis = async (): Promise<void> => {
}
};

export const deleteCachedPosts = async (collegeId: string): Promise<void> => {
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;

0 comments on commit 2021ab8

Please sign in to comment.