umami/src/lib/cache.ts

83 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-11-20 09:48:13 +01:00
import { User, Website } from '@prisma/client';
2022-12-27 06:51:16 +01:00
import redis from '@umami/redis-client';
2023-07-30 07:03:34 +02:00
import { getSession, getUserById, getWebsiteById } from '../queries';
2022-11-20 09:48:13 +01:00
async function fetchWebsite(id): Promise<Website> {
2023-10-20 22:05:31 +02:00
return redis.getCache(`website:${id}`, () => getWebsiteById(id), 86400);
}
async function storeWebsite(data) {
const { id } = data;
const key = `website:${id}`;
2023-10-20 22:05:31 +02:00
const obj = await redis.setCache(key, data);
2023-09-22 01:30:15 +02:00
await redis.expire(key, 86400);
return obj;
}
async function deleteWebsite(id) {
2023-10-20 22:05:31 +02:00
return redis.deleteCache(`website:${id}`);
}
2022-11-20 09:48:13 +01:00
async function fetchUser(id): Promise<User> {
2023-10-20 22:05:31 +02:00
return redis.getCache(`user:${id}`, () => getUserById(id, { includePassword: true }), 86400);
}
async function storeUser(data) {
const { id } = data;
const key = `user:${id}`;
2023-10-20 22:05:31 +02:00
const obj = await redis.setCache(key, data);
2023-09-22 01:30:15 +02:00
await redis.expire(key, 86400);
return obj;
}
async function deleteUser(id) {
2023-10-20 22:05:31 +02:00
return redis.deleteCache(`user:${id}`);
}
async function fetchSession(id) {
2023-10-20 22:05:31 +02:00
return redis.getCache(`session:${id}`, () => getSession(id), 86400);
}
async function storeSession(data) {
const { id } = data;
const key = `session:${id}`;
2023-10-20 22:05:31 +02:00
const obj = await redis.setCache(key, data);
2023-09-22 01:30:15 +02:00
await redis.expire(key, 86400);
return obj;
}
async function deleteSession(id) {
2023-10-20 22:05:31 +02:00
return redis.deleteCache(`session:${id}`);
}
2023-05-16 05:41:12 +02:00
async function fetchUserBlock(userId: string) {
const key = `user:block:${userId}`;
return redis.get(key);
}
2023-06-01 20:54:24 +02:00
async function incrementUserBlock(userId: string) {
const key = `user:block:${userId}`;
return redis.incr(key);
}
export default {
fetchWebsite,
storeWebsite,
deleteWebsite,
fetchUser,
storeUser,
deleteUser,
fetchSession,
storeSession,
deleteSession,
2023-05-16 05:41:12 +02:00
fetchUserBlock,
2023-06-01 20:54:24 +02:00
incrementUserBlock,
2023-09-22 01:30:15 +02:00
enabled: !!redis,
};