final product
This commit is contained in:
45
tools/redisDAL.js
Normal file
45
tools/redisDAL.js
Normal file
@@ -0,0 +1,45 @@
|
||||
const { createClient } = require("redis");
|
||||
|
||||
class RedisDAL {
|
||||
constructor() {
|
||||
this.client = createClient({ url:"redis://my-redis:6379" });
|
||||
|
||||
this.client.on("error", (err) => {
|
||||
console.error("Redis Client Error", err);
|
||||
});
|
||||
}
|
||||
|
||||
async connect() {
|
||||
if (!this.client.isOpen) {
|
||||
await this.client.connect();
|
||||
console.log("Connected to Redis");
|
||||
}
|
||||
}
|
||||
|
||||
generateKey(prefix, params) {
|
||||
const paramString = Object.entries(params)
|
||||
.sort()
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("&");
|
||||
return `${prefix}:${paramString}`;
|
||||
}
|
||||
|
||||
async get(prefix, params) {
|
||||
const key = this.generateKey(prefix, params);
|
||||
const cached = await this.client.get(key);
|
||||
if (cached) return JSON.parse(cached);
|
||||
return null;
|
||||
}
|
||||
|
||||
async set(prefix, params, data, ttl = 3600) {
|
||||
const key = this.generateKey(prefix, params);
|
||||
await this.client.set(key, JSON.stringify(data), { EX: ttl });
|
||||
}
|
||||
|
||||
async del(prefix, params) {
|
||||
const key = this.generateKey(prefix, params);
|
||||
await this.client.del(key);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new RedisDAL();
|
||||
Reference in New Issue
Block a user