Spaces:
Runtime error
Runtime error
File size: 2,932 Bytes
146b1cb 5906edb 146b1cb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
/**
* 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();
}
}
|