Updated redis logic.

This commit is contained in:
Mike Cao 2025-02-10 21:07:18 -08:00
parent 39e7ceac06
commit 4d6ec631f7
9 changed files with 52 additions and 46 deletions

View file

@ -1,6 +1,6 @@
import bcrypt from 'bcryptjs';
import { Report } from '@prisma/client';
import { getClient, redisEnabled } from '@umami/redis-client';
import redis from '@/lib/redis';
import debug from 'debug';
import { PERMISSIONS, ROLE_PERMISSIONS, ROLES, SHARE_TOKEN_HEADER } from '@/lib/constants';
import { secret, getRandomChars } from '@/lib/crypto';
@ -31,10 +31,8 @@ export async function checkAuth(request: Request) {
if (userId) {
user = await getUser(userId);
} else if (redisEnabled && authKey) {
const redis = getClient();
const key = await redis.get(authKey);
} else if (redis.enabled && authKey) {
const key = await redis.client.get(authKey);
if (key?.userId) {
user = await getUser(key.userId);
@ -66,12 +64,12 @@ export async function checkAuth(request: Request) {
export async function saveAuth(data: any, expire = 0) {
const authKey = `auth:${getRandomChars(32)}`;
const redis = getClient();
if (redis.enabled) {
await redis.client.set(authKey, data);
await redis.set(authKey, data);
if (expire) {
await redis.expire(authKey, expire);
if (expire) {
await redis.client.expire(authKey, expire);
}
}
return createSecureToken({ authKey }, secret());

View file

@ -1,14 +1,12 @@
import { Website, Session } from '@prisma/client';
import { getClient, redisEnabled } from '@umami/redis-client';
import redis from '@/lib/redis';
import { getWebsiteSession, getWebsite } from '@/queries';
export async function fetchWebsite(websiteId: string): Promise<Website> {
let website = null;
if (redisEnabled) {
const redis = getClient();
website = await redis.fetch(`website:${websiteId}`, () => getWebsite(websiteId), 86400);
if (redis.enabled) {
website = await redis.client.fetch(`website:${websiteId}`, () => getWebsite(websiteId), 86400);
} else {
website = await getWebsite(websiteId);
}
@ -23,10 +21,8 @@ export async function fetchWebsite(websiteId: string): Promise<Website> {
export async function fetchSession(websiteId: string, sessionId: string): Promise<Session> {
let session = null;
if (redisEnabled) {
const redis = getClient();
session = await redis.fetch(
if (redis.enabled) {
session = await redis.client.fetch(
`session:${sessionId}`,
() => getWebsiteSession(websiteId, sessionId),
86400,

17
src/lib/redis.ts Normal file
View file

@ -0,0 +1,17 @@
import { REDIS, UmamiRedisClient } from '@umami/redis-client';
const enabled = !!process.env.REDIS_URL;
function getClient() {
const client = new UmamiRedisClient(process.env.REDIS_URL);
if (process.env.NODE_ENV !== 'production') {
global[REDIS] = client;
}
return client;
}
const client = global[REDIS] || getClient();
export default { client, enabled };