* Generic method for sending an outgoing message of an arbitrary type. The main difference between this method and * addOutgoingEvent() is that this method does not use a queue so it can only be used while the client is ready * to send messages (in the 'ready' substate of the 'connected' state
(type: string, body = {})
| 506 | * @param body the message body |
| 507 | */ |
| 508 | public send(type: string, body = {}): Promise<number> { |
| 509 | const message = Object.assign({}, body, { |
| 510 | type, |
| 511 | id: this.nextMessageId(), |
| 512 | }); |
| 513 | |
| 514 | return new Promise((resolve, reject) => { |
| 515 | this.logger.debug(`send() in state: ${this.stateMachine.getStateHierarchy()}`); |
| 516 | if (this.websocket === undefined) { |
| 517 | this.logger.error('cannot send message when client is not connected'); |
| 518 | reject(sendWhileDisconnectedError()); |
| 519 | } else if (!(this.stateMachine.getCurrentState() === 'connected' && |
| 520 | this.stateMachine.getStateHierarchy()[1] === 'ready')) { |
| 521 | this.logger.error('cannot send message when client is not ready'); |
| 522 | reject(sendWhileNotReadyError()); |
| 523 | } else { |
| 524 | // NOTE: future feature request: middleware pipeline to process the message before its sent |
| 525 | this.emit('outgoing_message', message); |
| 526 | |
| 527 | const flatMessage = JSON.stringify(message); |
| 528 | this.logger.debug(`sending message on websocket: ${flatMessage}`); |
| 529 | |
| 530 | this.websocket.send(flatMessage, (error) => { |
| 531 | if (error !== undefined) { |
| 532 | this.logger.error(`failed to send message on websocket: ${error.message}`); |
| 533 | return reject(websocketErrorWithOriginal(error)); |
| 534 | } |
| 535 | resolve(message.id); |
| 536 | }); |
| 537 | } |
| 538 | }); |
| 539 | } |
| 540 | |
| 541 | /** |
| 542 | * Atomically increments and returns a message ID for the next message. |
no test coverage detected