idempotency-redis
Version:
Idempotency guarantee via Redis
67 lines (66 loc) • 2.67 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisCache = void 0;
const cache_errors_1 = require("./cache.errors");
// Class representing a wrapper around Redis operations for caching.
class RedisCache {
/**
* Constructs an instance of RedisCache.
* @param redis A RedisClientType instance for Redis operations.
*/
constructor(redis) {
this.redis = redis;
}
/**
* Retrieves a cached result by key.
* @param key The cache key to retrieve the value for.
* @returns A promise that resolves to a CachedResult or null if the key is not found.
*/
get(key) {
return __awaiter(this, void 0, void 0, function* () {
try {
const { type, error, value } = yield this.redis.hgetall(key);
if (!type) {
// If there's no type, the key doesn't exist in cache.
return null;
}
if (type === 'error') {
return {
type: 'error',
error,
};
}
return value ? { type: 'value', value } : { type: 'value' };
}
catch (error) {
throw new cache_errors_1.RedisCacheError('Failed to get cached result', key, error);
}
});
}
/**
* Sets a value in the cache.
* @param key The cache key to set the value for.
* @param value The CachedResult to store.
* @returns A promise that resolves when the operation is complete.
*/
set(key, value) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.redis.hset(key, value);
}
catch (error) {
throw new cache_errors_1.RedisCacheError('Failed to set cached result', key, error);
}
});
}
}
exports.RedisCache = RedisCache;