pollo/src/server/redis.ts

44 lines
942 B
TypeScript
Raw Normal View History

2023-06-18 23:45:04 -06:00
import { Redis } from "@upstash/redis";
2023-06-29 00:16:47 -06:00
import https from "https";
2023-07-03 15:37:14 -06:00
import { env } from "~/env.mjs";
2023-06-18 23:45:04 -06:00
2023-06-29 16:52:23 -06:00
export const redis = Redis.fromEnv({
2023-06-29 00:16:47 -06:00
agent: new https.Agent({ keepAlive: true }),
2023-06-18 23:45:04 -06:00
});
2023-07-03 15:37:14 -06:00
export const setCache = async <T>(key: string, value: T) => {
try {
2023-08-12 17:12:42 -06:00
console.log("KEY: ", key);
2023-07-03 15:37:14 -06:00
await redis.set(`${env.APP_ENV}_${key}`, value, {
ex: Number(env.UPSTASH_REDIS_EXPIRY_SECONDS),
});
return true;
} catch {
return false;
}
};
export const fetchCache = async <T>(key: string) => {
try {
const result = await redis.get(`${env.APP_ENV}_${key}`);
if (result) {
console.log("CACHE HIT");
} else {
console.log("CACHE MISS");
}
return result as T;
} catch {
console.log("CACHE ERROR");
return null;
}
};
export const invalidateCache = async (key: string) => {
try {
await redis.del(`${env.APP_ENV}_${key}`);
return true;
} catch {
return false;
}
};