feat: add redis (#242)
* feat: add refis * feat: add redis package Co-authored-by: Meier Lukas <meierschlumpf@gmail.com> * feat: add example docker compose, add redis connection in package * fix: usage of client after subscribe * feat: add logger for redis * refactor: format files Co-authored-by: Meier Lukas <meierschlumpf@gmail.com> --------- Co-authored-by: Meier Lukas <meierschlumpf@gmail.com>
This commit is contained in:
39
packages/redis/src/index.ts
Normal file
39
packages/redis/src/index.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Redis } from "ioredis";
|
||||
import superjson from "superjson";
|
||||
|
||||
import { logger } from "@homarr/log";
|
||||
|
||||
const subscriber = new Redis();
|
||||
const publisher = new Redis();
|
||||
const lastDataClient = new Redis();
|
||||
|
||||
const createChannel = <TData>(name: string) => {
|
||||
return {
|
||||
subscribe: (callback: (data: TData) => void) => {
|
||||
void lastDataClient.get(`last-${name}`).then((data) => {
|
||||
if (data) {
|
||||
callback(superjson.parse(data));
|
||||
}
|
||||
});
|
||||
void subscriber.subscribe(name, (err) => {
|
||||
if (!err) {
|
||||
return;
|
||||
}
|
||||
logger.error(
|
||||
`Error with channel '${name}': ${err.name} (${err.message})`,
|
||||
);
|
||||
});
|
||||
subscriber.on("message", (channel, message) => {
|
||||
if (channel !== name) return;
|
||||
|
||||
callback(superjson.parse(message));
|
||||
});
|
||||
},
|
||||
publish: async (data: TData) => {
|
||||
await lastDataClient.set(`last-${name}`, superjson.stringify(data));
|
||||
await publisher.publish(name, superjson.stringify(data));
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const exampleChannel = createChannel<{ message: string }>("example");
|
||||
Reference in New Issue
Block a user