mqtt-typedi
v0.1.2
Published
mqtt publisher/consumer decorators for nodejs
Downloads
4
Maintainers
Readme
mqtt-typedi
About
An elegant way to use publisher/consumer pattern with MQTT in Typedi container. Project is dependent on typedi container & mqtt
Installation
- peer dependencies
npm install mqtt typedi --save
- package
npm install mqtt-typedi --save
Enable decorators/metadata options in tsconfig.json
{
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
Usage
Create client and set it into Typedi container under Client
type key
import { Container } from 'typedi';
import * as mqtt from 'mqtt';
import { Client } from 'mqtt';
const client = mqtt.connect('mqtt://localhost', {
username: 'admin',
password: 'public',
});
Container.set(Client, client);
Publisher.ts
import { Service } from 'typedi';
import { Publisher, PublisherInterface } from 'mqtt-typedi';
@Service()
@Publisher('cool')
export class CoolPublisher implements PublisherInterface {
publish(message: string): any {
return message;
}
}
another_file.ts
import { CoolPublisher } from './CoolPublisher';
import { Container } from 'typedi';
const publisher = Container.get<CoolPublisher>(CoolPublisher);
publisher.publish('Hello mqtt-typedi');
Consumer.ts
import { Service } from 'typedi';
import { Consumer, ConsumerInterface } from 'mqtt-typedi';
@Service()
@Consumer('cool')
export class CoolConsumer implements ConsumerInterface {
consume(topic: string, message: string): any {
console.log({ topic, message }); // method will be called when new message appears on `cool` topic
}
}
another_file.ts
import { CoolConsumer } from './CoolConsumer';
const consumer = new CoolConsumer(); //initialize consumer
Subscribe options
In Publisher/Consumer decorators is available to pass subscribe options, however this is not mandatory, default QoS is 0
to pass options
@Publisher('cool', {
qos: 2,
rh: true,
...
})
same for consumer