(
event: string,
data?: any,
timeout = 6000,
force = false
)
| 24 | |
| 25 | // request to remote daemon |
| 26 | public async request<T = any>( |
| 27 | event: string, |
| 28 | data?: any, |
| 29 | timeout = 6000, |
| 30 | force = false |
| 31 | ): Promise<T> { |
| 32 | if (!this.rService || !this.rService.socket) throw new Error($t("TXT_CODE_3d94ea16")); |
| 33 | if (!this.rService.available && !force) |
| 34 | throw new Error($t("TXT_CODE_b7d38e78") + ` IP: ${this.rService.config.ip}`); |
| 35 | if (!this.rService.socket.connected && !force) |
| 36 | throw new Error($t("TXT_CODE_7c650d80") + ` IP: ${this.rService.config.ip}`); |
| 37 | |
| 38 | return new Promise((resolve, reject) => { |
| 39 | let countdownTask: NodeJS.Timeout; |
| 40 | const uuid = [v4(), new Date().getTime()].join(""); |
| 41 | const protocolData: IRequestPacket = { uuid, data }; |
| 42 | |
| 43 | const fn = (msg: IPacket) => { |
| 44 | if (msg.uuid === uuid) { |
| 45 | if (countdownTask) clearTimeout(countdownTask); |
| 46 | this.rService?.socket?.removeListener(event, fn); |
| 47 | if (msg.status == RemoteService.STATUS_OK) resolve(msg.data); |
| 48 | else if (msg.data.err) { |
| 49 | reject(new RemoteError(msg.data.err)); |
| 50 | } else { |
| 51 | reject(new RemoteError(msg.data)); |
| 52 | } |
| 53 | } |
| 54 | }; |
| 55 | |
| 56 | if (timeout) { |
| 57 | countdownTask = setTimeout(() => { |
| 58 | this.rService?.socket?.removeListener(event, fn); |
| 59 | reject( |
| 60 | new RemoteRequestTimeoutError( |
| 61 | [$t("TXT_CODE_bd99b64e"), this.rService?.config.ip].join(" ") |
| 62 | ) |
| 63 | ); |
| 64 | }, timeout); |
| 65 | } |
| 66 | |
| 67 | this.rService?.socket?.on(event, fn); |
| 68 | // send command |
| 69 | this.rService?.emit(event, protocolData); |
| 70 | }); |
| 71 | } |
| 72 | } |
no test coverage detected