tedis2
Version:
redis client for node.js with typescript and async
114 lines (113 loc) • 3.43 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Base = void 0;
const net_1 = require("net");
const tls_1 = require("tls");
const uuid_1 = require("uuid");
// core
const protocol_1 = require("./protocol");
class Base {
constructor(options = {}) {
this.id = uuid_1.v4();
if (typeof options.tls !== "undefined") {
this.socket = tls_1.connect({
host: options.host || "127.0.0.1",
port: options.port || 6379,
key: options.tls.key,
cert: options.tls.cert,
});
}
else {
this.socket = net_1.createConnection({
host: options.host || "127.0.0.1",
port: options.port || 6379,
});
}
this.protocol = new protocol_1.Protocol();
this.callbacks = [];
this.init();
if ("number" === typeof options.timeout) {
this.socket.setTimeout(options.timeout);
}
if ("string" === typeof options.password) {
this.auth(options.password);
}
}
command(...parameters) {
return new Promise((resolve, reject) => {
this.callbacks.push((err, res) => {
err ? reject(res) : resolve(res);
});
this.socket.write(this.protocol.encode(...parameters));
});
}
close() {
this.socket.end();
}
on(event, listener) {
switch (event) {
case "connect":
this.handle_connect = listener;
break;
case "timeout":
this.handle_timeout = listener;
break;
case "error":
this.handle_error = listener;
break;
case "close":
this.handle_close = listener;
break;
default:
throw new Error("event not found");
}
}
async auth(password) {
try {
return await this.command("AUTH", password);
}
catch (error) {
this.socket.emit("error", error);
this.socket.end();
}
}
init() {
this.socket.on("connect", () => {
if ("function" === typeof this.handle_connect) {
this.handle_connect();
}
});
this.socket.on("timeout", () => {
if ("function" === typeof this.handle_timeout) {
this.handle_timeout();
}
else {
this.close();
}
});
this.socket.on("error", err => {
if ("function" === typeof this.handle_error) {
this.handle_error(err);
}
else {
console.log("error:", err);
}
});
this.socket.on("close", (had_error) => {
if ("function" === typeof this.handle_close) {
this.handle_close(had_error);
}
});
this.socket.on("data", data => {
this.protocol.write(data);
while (true) {
this.protocol.parse();
if (!this.protocol.data.state) {
break;
}
this.callbacks.shift()(this.protocol.data.res.error, this.protocol.data.res.data);
}
});
}
}
exports.Base = Base;