can i separate function connection and subcription on MQTT?

20 views Asked by At

so i have code mqtt connection and subcription where the are in one line like this

import mqtt from 'mqtt';

const brokerUrl = 'mqtt://mqtt.example.com';
const client = mqtt.connect(brokerUrl);

const mqttConnect = () => {
    client.on('connect', () => {
        console.log('Connection on broker MQTT.');
    });

    client.subscribe('topic/test', (err) => {
            if (!err) {
                console.log('Subcription on Topic.');
            }
        });

    client.on('message', (topic, message) => {
        console.log('Message :', message.toString());
    });

    client.on('error', (error) => {
        console.error('MQTT error :', error);
    });
};

export default mqttConnect;

but i want to separate function connection and subcription i try with this code

mqttConnect.js

import mqtt from 'mqtt';

const brokerUrl = 'mqtt://mqtt.example.com';
const client = mqtt.connect(brokerUrl);

const connect = () => {
    console.log('Connection on broker MQTT.');
    return client;
};

export default connect;

mqttSubcription.js

import connect from './mqttConnect';

const subscription = () => {
    const client = connect(); 

    client.subscribe('topic/test', (err) => {
        if (!err) {
            console.log('Subcription on topic test.');
        }
    });

    client.on('message', (topic, message) => {
        console.log('message:', message.toString());
    });
};

export default subscription;

but i have error issue said : TypeError: client.subscribe is not a function

can i really separate the function ? or my method is wrong ? can you suggest the right method?

0

There are 0 answers