DwightAI / cache.js
sujoydev99's picture
redis added
5906edb
/**
* A simple in-memory cache implementation
*/
import { Redis } from 'ioredis';
export class RedisListCache {
constructor(params = {}) {
this.redis = new Redis({
host: 'redis-12291.c305.ap-south-1-1.ec2.cloud.redislabs.com',
port: 12291,
password: 'KQCVapXXF2ioM4zF5krQFImzAYkKWY5l',
username: "default"
})
this.namespace = params.namespace ? params.namespace + ':' : '';
}
// Get a value from the list
async getItem(key, index) {
const namespacedKey = this.namespace + key;
const item = await this.redis.lindex(namespacedKey, index);
return item ? JSON.parse(item) : null;
}
// Get a value from the list
async updateItem(key, index, newValue) {
const namespacedKey = this.namespace + key;
const length = await this.redis.llen(namespacedKey);
if (index >= length) {
throw new Error('Index out of range');
}
// Update the item at the specified index
await this.redis.lset(namespacedKey, index, JSON.stringify(newValue));
}
// Get a all keys
async keys(key) {
const namespacedKey = this.namespace + key;
return this.redis.keys(namespacedKey);
}
// check if key exists
async exists(key, index) {
const namespacedKey = this.namespace + key;
const item = await this.redis.exists(namespacedKey);
return item;
}
// Set multiple values in the list
async setItems(key, ...values) {
const namespacedKey = this.namespace + key;
const items = values.map(value => JSON.stringify({
...value,
}));
await this.redis.rpush(namespacedKey, ...items);
}
// Remove a value from the list
async removeItem(key, count, value) {
const namespacedKey = this.namespace + key;
const item = JSON.stringify(value);
return this.redis.lrem(namespacedKey, count, item);
}
// Get the length of the list
async length(key) {
const namespacedKey = this.namespace + key;
return this.redis.llen(namespacedKey);
}
// Get all items from the list
async getAll(key, page, limit) {
const namespacedKey = this.namespace + key;
const items = await this.redis.lrange(namespacedKey, 0, -1);
if (page && limit) {
const startIndex = (page - 1) * limit;
const endIndex = startIndex + limit;
const _items = items.slice(startIndex, endIndex);
return _items.map(item => JSON.parse(item));
}
return items.map(item => JSON.parse(item));
}
// Remove all items from the list
async clear(key) {
const namespacedKey = this.namespace + key;
return this.redis.del(namespacedKey);
}
// Close the Redis connection
async close() {
await this.redis.quit();
}
}