Created
January 24, 2023 03:08
-
-
Save AnthonyLzq/ff99d1dcff9e127dada42cfbca401c71 to your computer and use it in GitHub Desktop.
Script to create a route to listen using MQTT
This file contains 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
import { MqttClient } from 'mqtt' | |
import { UserServices } from 'services' | |
const PUB_TOPIC = 'DoorCloud' | |
const SUB_TOPIC = `\${PUB_TOPIC}/photo` | |
const sub = (client: MqttClient) => { | |
const subDebugger = 'DoorCloud:Mqtt:demo:sub' | |
client.subscribe(SUB_TOPIC, error => { | |
if (!error) console.log(`Subscribed to ${subDebugger}`) | |
}) | |
client.on('error', error => { | |
console.error(error, `Topic: ${SUB_TOPIC} - Error`) | |
}) | |
/** | |
* The message received will be a string in the following format: | |
* userID--format--base64Photo | |
*/ | |
client.on('message', async (topic, message) => { | |
if (topic.includes('photo')) { | |
console.log('Received a photo') | |
const [userID, format, base64] = message.toString().split('----') | |
const [, base64Photo] = base64 | |
.split(`data:image/${format};base64,`) | |
const us = new UserServices(log) | |
try { | |
await us.sendPhotoThroughWhatsapp( | |
userID, | |
format, | |
Buffer.from(base64Photo, 'base64') | |
) | |
console.log(`Topic: ${SUB_TOPIC} - Photo send.`) | |
} catch (error) { | |
const errorMessage = 'Error while sending the image to the user' | |
console.error(errorMessage, error) | |
throw new Error(errorMessage) | |
} | |
} | |
}) | |
} | |
const demo: Route = { | |
sub, | |
PUB_TOPIC, | |
SUB_TOPIC | |
} | |
export { demo } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment