UNPKG

@lucsoft/network-connector

Version:

Network Connector the easy way to connect to your HmSYS Network

57 lines (56 loc) 1.73 kB
export class Fetcher { hmsys; counter = 0; syncEvents = []; eventsHolder = {}; constructor(hmsys) { this.hmsys = hmsys; this.hmsys().rawOn(8 /* Message */, ({ data }) => Object.keys(this.eventsHolder).forEach(x => this.eventsHolder[x](data))); this.hmsys().rawOn(8 /* Message */, ({ data }) => { if (data.type !== "sync") return; this.syncEvents.filter(x => x.type == data.data.type).forEach(x => x.recivedData(data.data)); }); } requestUserData(...data) { return this.customRequest({ action: "account", type: data }); } sync = (type, recivedData) => { this.syncEvents.push({ type, recivedData }); return this; }; customRequest(initialRequest) { return new Promise((resolve, reject) => { const id = (this.counter++).toString(); const timeout = setTimeout(() => { reject(0 /* Timeout */); }, this.hmsys().timeout); this.hmsys().sendWithAuth({ id, ...initialRequest }); this.eventsHolder[id] = (data) => { if (data.id === id) { clearTimeout(timeout); resolve(data); delete this.eventsHolder[id.toString()]; } }; }); } trigger(id, data) { this.hmsys().sendWithAuth({ id, action: "trigger", type: id, data }); } triggerWithResponse(id, data) { return this.customRequest({ action: "trigger", type: id, data }); } }