pollo/app/services/redis.server.ts

121 lines
2.7 KiB
TypeScript
Raw Permalink Normal View History

2023-12-01 14:57:31 -07:00
import Redis from "ioredis";
2023-12-04 23:18:24 -07:00
let cache: Redis | null = null;
let pub: Redis | null = null;
let sub: Redis | null = null;
declare global {
var __cache: Redis | null;
var __pub: Redis | null;
var __sub: Redis | null;
}
if (process.env.NODE_ENV === "production") {
cache = process.env.REDIS_URL
? new Redis(process.env.REDIS_URL, {
family: 6,
})
: null;
} else {
if (!global.__cache) {
global.__cache = process.env.REDIS_URL
? new Redis(process.env.REDIS_URL, {
family: 6,
})
: null;
}
cache = global.__cache;
}
if (process.env.NODE_ENV === "production") {
pub = process.env.REDIS_URL
? new Redis(process.env.REDIS_URL, {
family: 6,
})
: null;
} else {
if (!global.__pub) {
global.__pub = process.env.REDIS_URL
? new Redis(process.env.REDIS_URL, {
family: 6,
})
: null;
}
pub = global.__pub;
}
if (process.env.NODE_ENV === "production") {
sub = process.env.REDIS_URL
? new Redis(process.env.REDIS_URL, {
family: 6,
})
: null;
} else {
if (!global.__sub) {
global.__sub = process.env.REDIS_URL
? new Redis(process.env.REDIS_URL, {
family: 6,
})
: null;
}
sub = global.__sub;
}
2023-12-01 14:57:31 -07:00
export const publishToChannel = async (channel: string, message: string) => {
await pub?.publish(channel, JSON.stringify(message));
};
export const subscribeToChannel = async (
channel: string,
callback: Function
) => {
await sub?.subscribe(channel, (err, count) => {
if (err) {
console.error("Failed to subscribe: %s", err.message);
} else {
console.log(
`Subscribed successfully! This client is currently subscribed to ${count} channels.`
);
}
});
sub?.on("message", (channel, message) => {
console.log(`Received ${message} from ${channel}`);
callback(message);
});
};
export const unsubscribeToChannel = (channel: string) => {
2023-12-13 14:52:56 -07:00
console.log(`Unsubscribed successfully from ${channel}!`);
2023-12-01 14:57:31 -07:00
Promise.resolve([sub?.unsubscribe(channel)]);
};
2023-12-01 16:15:21 -07:00
export const setCache = async <T>(key: string, value: T, prefix?: string) => {
2023-12-01 14:57:31 -07:00
try {
2023-12-01 16:15:21 -07:00
await cache?.set(prefix ? `${prefix}_${key}` : key, JSON.stringify(value));
2023-12-01 14:57:31 -07:00
return true;
} catch {
return false;
}
};
2023-12-01 16:15:21 -07:00
export const fetchCache = async <T>(key: string, prefix?: string) => {
2023-12-01 14:57:31 -07:00
try {
2023-12-01 16:15:21 -07:00
const result = (await cache?.get(
prefix ? `${prefix}_${key}` : key
)) as string;
2023-12-01 14:57:31 -07:00
return JSON.parse(result) as T;
} catch {
return null;
}
};
2023-12-01 16:15:21 -07:00
export const invalidateCache = async (key: string, prefix?: string) => {
2023-12-01 14:57:31 -07:00
try {
2023-12-01 16:15:21 -07:00
await cache?.del(prefix ? `${prefix}_${key}` : key);
2023-12-01 14:57:31 -07:00
return true;
} catch {
return false;
}
};