@sophons/redis
Version:
🏡 Encapsulate common business methods for Redis
78 lines (77 loc) • 3.09 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.hashCacheDecorator = exports.cacheDecorator = exports.mutexDecorator = void 0;
/**
* Decorator that performs mutex logic
*/
exports.mutexDecorator = (client, options) => {
return {
with: (...args) => __awaiter(void 0, void 0, void 0, function* () {
try {
const status = yield client.set(options.key, 0, 'EX', options.ttl || 5, 'NX');
if (!status || status !== 'OK')
throw new Error(options.message || 'Frequent Operation');
// After successful execution, the mutex is released
const result = yield options.next(...args);
yield client.del(options.key);
return result;
}
catch (error) {
// Release the mutex no matter what happens
yield client.del(options.key);
throw new Error(error);
}
}),
};
};
/**
* Decorator that performs cache logic
*/
exports.cacheDecorator = (client, options) => {
return {
with: (...args) => __awaiter(void 0, void 0, void 0, function* () {
const record = yield client.get(options.key);
// return cache record
if (record)
return JSON.parse(record);
// call next with args
const result = yield options.next(...args);
// nothing ...
if (!result)
return null;
// cache next result
yield client.set(options.key, JSON.stringify(result), 'EX', options.ttl);
return result;
}),
};
};
/**
* Decorator that performs cache(hash) logic
*/
exports.hashCacheDecorator = (client, options) => {
return {
with: (...args) => __awaiter(void 0, void 0, void 0, function* () {
const record = yield client.hget(options.hkey, options.key);
// return cache record
if (record)
return JSON.parse(record);
// call next with args
const result = yield options.next(...args);
// nothing ...
if (!result)
return null;
// cache next result
yield client.hset(options.hkey, options.key, JSON.stringify(result));
return result;
}),
};
};