Wednesday 14 February 2018

Need help making a StompJs Wrapper

Im trying to create a class to communicate with stomp via node. Im using the stompit library.Basically what i want to do is have code like the following.var client = new AMQClient(host,port); client.sendMessage(destination,"Hello"); The problem here is that when doing a stompit.connect it doesnt just return the client. It goes to a callback which in there returns the client. Im new to nodeJs so Im trying to set this up properly. Ive looked up async/await and generators but i cant think how to make them workfunction connectCB(error, client, reconnect) { if (error) { console.log("Connect error:", error.message) return; } else { this.client = client; this.connected = true; console.log(`Connected to: ${this.host}:${this.port}`); } this.client.on("error", (error) => { this.connected = false; console.log(error) console.log("Trying to reconnect....") reconnect(); }) } class AMQClient { constructor(host, port) { this.host = host; this.port = port; this.connectionOptions = { host, port } this.reconnectOptions = { maxReconnects: 10 }; this.connected = false; this.manager = new stomp.ConnectFailover([this.connectionOptions], this.reconnectOptions); this.connect() } connect() { console.log(`Connecting to: ${this.host}:${this.port}`); this.manager.connect(connectCB.bind(this)) // stomp.connect(this.connectionOptions, connectCB.bind(this)); deasync.loopWhile(this.isNotConnected.bind(this)); //Syncronize the connection } sendMessage(destination, message) { if (this.connected) { var frame = this.client.send({ destination }); frame.write(message); frame.end(); } else { console.log("Error sending message:No connection to AMQ") } } subscribe(destination, callback) { this.client.subscribe(destination, callback) } getMessageBody(message) { var result = null; console.log("Before reading", result) message.readString('utf-8', function(error, body) { console.log("In reading", result) if (error) { console.log('read message error ' + error.message); return; } result = body; }); console.log("before desync", result) deasync.loopWhile(function() { result != null }); console.log("After desync", result) return result; } isConnected() { return this.connected; } isNotConnected() { return !this.connected; } } I got something like that working so far but im not sure its the best way of doing things. I tried to make the connect function an Async function then doing an await on it but then when i run client.sendMessage it gives the error that its not connected. Any suggestions would be appreciated.

Submitted February 14, 2018 at 08:48PM by ponzi314

No comments:

Post a Comment