@lucsoft/network-connector
Version:
Network Connector the easy way to connect to your HmSYS Network
85 lines (84 loc) • 3.5 kB
JavaScript
import { Fetcher } from './data/Fetcher';
import { RestFetcher } from './data/RestFetcher';
import { saveInLocalStorageProvider } from "./auth/SaveInLocalStorage";
export { saveInLocalStorageProvider as createLocalStorageProvider } from './auth/SaveInLocalStorage';
export * from './events/EventAction';
export * from './events/EventTypes';
export class NetworkConnector {
url;
#events = [];
#socket = undefined;
#options;
api;
rest;
timeout = 1000;
constructor(url, options = { store: saveInLocalStorageProvider() }) {
this.url = url;
this.#options = options;
this.api = new Fetcher(() => this);
this.rest = new RestFetcher(() => this, this.#options.AllowNonHTTPSConnection ?? false);
}
rawOn = (type, action) => { this.#events.push({ action, type }); return this; };
sendWithAuth = (data) => this.#socket?.send(JSON.stringify({ ...data, auth: this.getAuth() }));
send = (data) => {
if (typeof data == "object") {
this.#socket?.send(JSON.stringify(data));
}
else
this.#socket?.send(data);
};
authorize(email, password) {
this.send({
action: "login",
type: "client",
email,
password
});
}
restart() {
this.#socket?.close();
this.#socket == undefined;
this.ready();
}
ready() {
if (this.#socket && [0, 1].includes(this.#socket.readyState))
return true;
this.#socket = new WebSocket((this.#options.AllowNonHTTPSConnection ? "ws://" : "wss://") + this.url);
this.emitEvent(0 /* Connecting */, { socket: this.#socket });
this.#socket.onmessage = (x) => {
try {
const data = JSON.parse(x.data);
this.emitEvent(7 /* RawMessage */, { data, socket: this.#socket });
if (data.login === "require authentication") {
this.emitEvent(3 /* TryingLogin */, { socket: this.#socket });
const relogin = this.#options.store.getReloginDetails();
if (relogin)
this.send({ action: "login", type: "client", token: relogin.token, id: relogin.id });
else
this.emitEvent(5 /* CredentialsRequired */, { socket: this.#socket });
}
else if (data.login === false) {
this.emitEvent(4 /* LoginFailed */, { socket: this.#socket });
}
else if (data.login === true) {
this.#options.store.setReloginDetails(data.client);
this.emitEvent(6 /* LoginSuccessful */, { socket: this.#socket, data });
}
else {
this.emitEvent(8 /* Message */, { socket: this.#socket, data });
}
}
catch (error) {
console.error(error);
}
};
this.#socket.onopen = () => this.emitEvent(1 /* Conncted */, { socket: this.#socket });
this.#socket.onclose = () => this.emitEvent(2 /* Disconnected */, { socket: this.#socket });
this.#socket.onerror = () => this.emitEvent(2 /* Disconnected */, { socket: this.#socket });
}
getAuth = () => this.#options.store?.getReloginDetails();
emitEvent(type, data) {
this.#events.filter(x => x.type == type).forEach(x => x.action(data));
return this;
}
}