nope/lib/communication/mirrors/ioSocketMirrorClient.ts
2021-08-17 17:52:46 +02:00

61 lines
1.8 KiB
TypeScript

/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2021-03-22 19:03:15
* @modify date 2021-04-09 08:34:22
* @desc [description]
*/
import { connect } from "socket.io-client";
import { getNopeLogger } from "../../logger/getLogger";
import { LoggerLevel } from "../../logger/nopeLogger";
import { EventMirror } from "./eventMirror";
/**
* Mirror Layer using IO-Sockets.
*
* @export
* @class IoSocketMirrorClient
*/
export class IoSocketMirrorClient extends EventMirror {
/**
* Creates an instance of IoSocketMirrorClient.
* @param {string} uri Uri of the Server.
* @param {LoggerLevel} [level="info"] Logger level
* @memberof IoSocketMirrorClient
*/
constructor(public uri: string, level: LoggerLevel = "info") {
super(
// As event Emitter, we provide the IO-Client.
connect(uri.startsWith("http://") ? uri : "http://" + uri) as any,
getNopeLogger("io-mirror-client", level)
);
// Make shure we use the http as starting of the uri.
this.uri = this.uri.startsWith("http://") ? this.uri : "http://" + this.uri;
this.receivesOwnMessages = false;
// Now, because we arent connected we set the connected flag to false,
// it will only be true, if a connection with the server has been established
// Therefore we will connect to the "connect" and "disconnect" event of the
// socket.
this.connected.setContent(false);
this._logger.info("connecting to: " + uri);
const _this = this;
this._emitter.on("connect", (...args) => {
// Element is connected
_this._logger.info("connected");
_this.connected.setContent(true);
});
this._emitter.on("disconnect", () => {
// Connection Lost.
_this._logger.error("Connection lost!");
_this.connected.setContent(false);
});
}
}