-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathmqtt.service.ts
46 lines (42 loc) · 1.34 KB
/
mqtt.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { Inject, Injectable } from '@nestjs/common';
import { MQTT_CLIENT_INSTANCE } from './mqtt.constants';
import { Client, Packet, IClientPublishOptions, IClientSubscribeOptions, ISubscriptionGrant } from 'mqtt';
@Injectable()
export class MqttService {
constructor(
@Inject(MQTT_CLIENT_INSTANCE) private readonly client: Client,
) {}
subscribe(topic: string | string[], opts?: IClientSubscribeOptions): Promise<ISubscriptionGrant[]> {
return new Promise((resolve, reject) => {
this.client.subscribe(topic, opts || null, (err, granted) => {
if (err) {
reject(err);
} else {
resolve(granted);
}
});
});
}
unsubscribe(topic: string, opts?: Record<string, any>): Promise<Packet> {
return new Promise<Packet>((resolve, reject) => {
this.client.unsubscribe(topic, opts || null, (error, packet) => {
if (error) {
reject(error);
} else {
resolve(packet);
}
});
});
}
publish(topic: string, message: string | Buffer | object, opts?: IClientPublishOptions): Promise<Packet> {
return new Promise<Packet>((resolve, reject) => {
this.client.publish(topic, message, opts || null, (error, packet) => {
if (error) {
reject(error);
} else {
resolve(packet);
}
});
});
}
}