Created
March 5, 2018 01:57
-
-
Save cagodoy/dba98feb46b0e6b038ffcd14f9428627 to your computer and use it in GitHub Desktop.
mqttAPI.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class MQTTAPI { | |
constructor (options) { | |
if (options && options.timeout) { | |
this.timeout = options.timeout | |
} else { | |
this.timeout = 3000 | |
} | |
} | |
get (client, topic) { | |
return new Promise((resolve, reject) => { | |
if (!client.isSubcribed(topic)) { | |
client.subscribe(topic) | |
} | |
if (typeof topic !== 'string') { | |
return reject(new Error(`invalid topic param in [GET] ${topic}`)) | |
} | |
const timeout = timeout(async () => { | |
return new Error(`timeout on [GET] ${topic}`) | |
}, this.timeout) | |
client.once(topic, async (response) => { | |
clearTimeout(timeout) | |
console.log('[MQTT GET]', topic, response) | |
client.unsubscribe(topic) | |
resolve(response) | |
}) | |
client.publish(topic, {}) | |
}) | |
} | |
post (client, topic, body) { | |
return new Promise((resolve, reject) => { | |
if (!client.isSubcribed(topic)) { | |
client.subscribe(topic) | |
} | |
if (typeof topic !== 'string') { | |
return reject(new Error(`invalid topic param in [POST] ${topic}`)) | |
} | |
if (typeof body !== 'object') { | |
return reject(new Error(`invalid body param in [POST] ${topic}`)) | |
} | |
const timeout = timeout(async () => { | |
return new Error(`timeout on [POST] ${topic}`) | |
}, this.timeout) | |
client.once(topic, async (response) => { | |
clearTimeout(timeout) | |
console.log('[MQTT POST]', topic, response) | |
client.unsubscribe(topic) | |
resolve(response) | |
}) | |
client.publish(topic, body) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment