# egg-mqtt

[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Test coverage][codecov-image]][codecov-url]
[![David deps][david-image]][david-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]
[![npm download][download-image]][download-url]

[npm-image]: https://img.shields.io/npm/v/egg-mqtt.svg?style=flat-square
[npm-url]: https://npmjs.org/package/egg-mqtt
[travis-image]: https://img.shields.io/travis/eggjs/egg-mqtt.svg?style=flat-square
[travis-url]: https://travis-ci.org/eggjs/egg-mqtt
[codecov-image]: https://img.shields.io/codecov/c/github/eggjs/egg-mqtt.svg?style=flat-square
[codecov-url]: https://codecov.io/github/eggjs/egg-mqtt?branch=master
[david-image]: https://img.shields.io/david/eggjs/egg-mqtt.svg?style=flat-square
[david-url]: https://david-dm.org/eggjs/egg-mqtt
[snyk-image]: https://snyk.io/test/npm/egg-mqtt/badge.svg?style=flat-square
[snyk-url]: https://snyk.io/test/npm/egg-mqtt
[download-image]: https://img.shields.io/npm/dm/egg-mqtt.svg?style=flat-square
[download-url]: https://npmjs.org/package/egg-mqtt

<!--
Description here.
-->

## Install

```bash
$ npm i @diyaner/egg-mqtt --save
```

## Usage

```js
// {app_root}/config/plugin.js
exports.mqtt = {
	enable: true,
	package: "@diyaner/egg-mqtt",
};
```

## Configuration

```js
// {app_root}/config/config.default.js
exports.mqtt = {
	enable: true,
	clients: [],
};
```

see [config/config.default.js](config/config.default.js) for more detail.

## Example

<!-- example here -->

在 app 上挂载 mqtt 客户端调用，发布订阅和接收消息。
在 agent 上挂载 mqtts 存储所有连接实例。

```ts
// 在app.ts中使用
// 推荐注册回调，当agent上mqtt连接完成后会触发回调来执行初始化逻辑
this.app.mqtt.onConnected(() => {
	const client = this.app.mqtt.get(this.app, "eggMQTTPluginTest");
	client.onMessage((topic, msg) => {
		console.log("topic", topic);
		console.log("msg", msg);
	});
	const opt: mqtt.IClientPublishOptions = {
		retain: false,
	};
	client.publish(
		"topic/abc/bcd",
		{ a: 1, b: 2 },
		{
			...opt,
		}
	);
	client.subscribe("hello/world", { qos: 2 });
});
// 其他情况，在service中调用发布，按正常使用即可。
// fetch api 通过payload的特殊字段messageId实现请求响应模型。要求消息消费者端必须携带返回messageId
```

## Questions & Suggestions

Please open an issue [here](https://github.com/eggjs/egg/issues).

## License

[MIT](LICENSE)
