redis-typescript
Version:
redis client for node.js with typescript and async
91 lines • 2.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const net_1 = require("net");
const uuid_1 = require("uuid");
// core
const protocol_1 = require("./protocol");
class Base {
constructor(options = {}) {
this.id = uuid_1.v4();
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.handle_connect = () => {
console.log("connect");
};
this.handle_timeout = () => {
console.log("timeout");
};
this.handle_error = (err) => {
console.log(err);
};
this.handle_close = (had_error) => {
console.log("close with error: ", had_error);
};
this.init();
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");
}
}
auth(password) {
return this.command("AUTH", password);
}
init() {
this.socket.on("connect", () => {
this.handle_connect();
});
this.socket.on("timeout", () => {
this.handle_timeout();
});
this.socket.on("error", (err) => {
this.handle_error(err);
});
this.socket.on("close", (had_error) => {
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;
//# sourceMappingURL=base.js.map