connect() {
		let Nats;
		try {
			Nats = require("nats");
		} catch (err) {
			/* istanbul ignore next */
			this.broker.fatal(
				"The 'nats' package is missing! Please install it with 'npm install nats --save' command.",
				err,
				true
			);
		}

		if (this.useLegacy) {
			return new this.broker.Promise((resolve, reject) => {
				const client = Nats.connect(this.opts);
				this._client = client; // For tests

				client.on("connect", () => {
					this.client = client;
					this.logger.info("NATS client v1 is connected.");
					this.onConnected().then(resolve);
				});

				/* istanbul ignore next */
				client.on("reconnect", () => {
					this.logger.info("NATS client is reconnected.");
					this.onConnected(true);
				});

				/* istanbul ignore next */
				client.on("reconnecting", () => {
					this.logger.warn("NATS client is reconnecting...");
				});

				/* istanbul ignore next */
				client.on("disconnect", () => {
					if (this.connected) {
						this.logger.warn("NATS client is disconnected.");
						this.connected = false;
					}
				});

				/* istanbul ignore next */
				client.on("error", e => {
					this.logger.error("NATS error.", e.message);
					this.logger.debug(e);

					this.broker.broadcastLocal("$transporter.error", {
						error: e,
						module: "transporter",
						type: C.CLIENT_ERROR
					});

					if (!client.connected) reject(e);
				});

				/* istanbul ignore next */
				client.on("close", () => {
					this.connected = false;
					// Hint: It won't try reconnecting again, so we kill the process.
					this.broker.fatal("NATS connection closed.");
				});
			});
		} else {
			// NATS v2
			if (this.opts.url) {
				Object.assign(
					this.opts,
					this.opts.url.split(",").reduce((acc, cur) => {
						const url = new URL(cur);

						acc.servers = Array.isArray(acc.servers)
							? acc.servers.concat(url.host)
							: [url.host];
						acc.user = acc.user || url.username || undefined;
						acc.pass = acc.pass || url.password || undefined;

						return acc;
					}, Object.create(null))
				);
			}

			return Nats.connect(this.opts)
				.then(client => {
					this.client = client;

					this.logger.info("NATS client v2 is connected.");

					(async () => {
						for await (const s of this.client.status()) {
							this.logger.debug(`NATS client ${s.type}: ${s.data}`);
						}
					})().then();

					client.closed().then(() => {
						this.connected = false;
						this.logger.info("NATS connection closed.");
					});

					return this.onConnected();
				})
				.catch(
					/* istanbul ignore next */ err => {
						this.logger.error("NATS error.", err.message);
						this.logger.debug(err);

						this.broker.broadcastLocal("$transporter.error", {
							error: err,
							module: "transporter",
							type: C.CLIENT_ERROR
						});

						throw err;
					}
				);
		}
	}
Connect to a NATS server

@memberof NatsTransporter