@micro.ts/core
Version:
Microservice framework with Typescript
96 lines (95 loc) • 3.66 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());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisClient = void 0;
const ioredis_1 = __importDefault(require("ioredis"));
class RedisClient {
constructor(config) {
this.config = config;
}
init() {
return __awaiter(this, void 0, void 0, function* () {
const _a = this.config, { url } = _a, options = __rest(_a, ["url"]);
return new Promise((resolve, reject) => {
this.redis = new ioredis_1.default(this.config.url, options);
this.redis.on('connect', () => {
console.log('Redis Connected on ', this.config.url);
resolve();
});
this.redis.on('error', (err) => {
reject(err);
});
});
});
}
get(key) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.redis) {
console.log('You forgot call init() method on the redis client!');
return null;
}
return this.redis.get(key);
});
}
set(key, value, ex) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.redis) {
console.log('You forgot call init() method on the redis client!');
return;
}
if (!ex) {
yield this.redis.set(key, value);
}
else {
yield this.redis.set(key, value, 'ex', ex);
}
});
}
delete(key) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.redis) {
console.log('You forgot call init() method on the redis client!');
return;
}
yield this.redis.del(key);
});
}
getJson(key) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.get(key);
if (!result) {
return null;
}
return JSON.parse(result);
});
}
setJson(key, value, ex) {
return __awaiter(this, void 0, void 0, function* () {
const str = JSON.stringify(value);
yield this.set(key, str, ex);
});
}
}
exports.RedisClient = RedisClient;