perf: cache banners with Redis #23

Merged
vivy-agent merged 1 commits from perf into main 2026-03-05 16:46:15 +07:00
2 changed files with 23 additions and 1 deletions
Showing only changes of commit afcd2348e0 - Show all commits

7
src/config/redis/key.ts Normal file
View File

@ -0,0 +1,7 @@
export const redisKey = [
{
name: "HERO_BANNER",
description: "Key for caching active hero banner data",
key: `${process.env.APP_NAME}:system:banner`,
},
];

View File

@ -1,10 +1,13 @@
import { redisKey } from "../../../config/redis/key";
import { AppError } from "../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { redis } from "../../../utils/databases/redis/connection";
import { findSystemPreferenceService } from "../../systemPreference/services/internal/findSystemPreference.service";
import { findAllActiveHeroBannerRepository } from "../repositories/GET/findAllActiveHeroBanner.repository";
export const getActiveHeroBannerService = async () => {
try {
// Check if Hero Banner is enabled in system preferences
const isHeroBannerEnabled = await findSystemPreferenceService(
"HERO_BANNER_ENABLED",
"boolean",
@ -12,7 +15,19 @@ export const getActiveHeroBannerService = async () => {
if (!isHeroBannerEnabled)
throw new AppError(403, "Hero Banner is disabled");
return await findAllActiveHeroBannerRepository();
// Try to get active banners from Redis cache
const cachedBanners = await redis.get(
`${redisKey.filter((key) => key.name === "HERO_BANNER")[0].key}`,
);
if (cachedBanners) return JSON.parse(cachedBanners);
// If not in cache, fetch from database and cache the result
const activeBanners = await findAllActiveHeroBannerRepository();
await redis.set(
`${redisKey.filter((key) => key.name === "HERO_BANNER")[0].key}`,
JSON.stringify(activeBanners),
);
return activeBanners;
} catch (error) {
ErrorForwarder(error);
}