const uuid = require('uuid').v4; class Message { needs_response = false; has_response = false; socket; sender; get socket_send() { if ( this.sender ) { return this.sender; } else { return (...args) => this.socket.send(...args); } } static route(route) { const msg = new this(); return msg.route(route); } constructor(message = '{}') { this._data = JSON.parse(message) this._uuid = this._data.uuid || uuid() } fresh() { const inst = new this.constructor() inst.socket = this.socket inst.sender = this.sender return inst } error(set = undefined) { if ( set ) { this._data.error = set; return this; } return this._data.error; } response_to(req_uuid = undefined) { if ( req_uuid ) { this._data.in_response_to = req_uuid; return this; } return this._data.in_response_to; } is_response() { return !!this._data.in_response_to; } route(set = undefined) { if ( set ) { this._data.route = set; return this; } return this._data.route; } data(set = undefined) { if ( set ) { this._data.data = set; return this; } return this._data.data; } uuid() { return this._uuid; } serialize() { return JSON.stringify({...this._data, uuid: this._uuid}); } expect_response(callback = () => {}) { this.needs_response = true; this._response_callback = callback; return this; } send_response(other_message) { other_message.response_to(this.uuid()) this.socket_send(other_message.serialize()) } } module.exports = exports = Message