fix(MQTT Node): Node hangs forever on failed connection (#10048)

This commit is contained in:
Michael Kret 2024-07-17 16:50:51 +03:00 committed by GitHub
parent 8a53d6127e
commit 76c290655d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,5 +1,5 @@
import { connectAsync, type IClientOptions, type MqttClient } from 'mqtt'; import { connect, type IClientOptions, type MqttClient } from 'mqtt';
import { randomString } from 'n8n-workflow'; import { ApplicationError, randomString } from 'n8n-workflow';
import { formatPrivateKey } from '@utils/utilities'; import { formatPrivateKey } from '@utils/utilities';
interface BaseMqttCredential { interface BaseMqttCredential {
@ -49,5 +49,23 @@ export const createClient = async (credentials: MqttCredential): Promise<MqttCli
clientOptions.rejectUnauthorized = credentials.rejectUnauthorized; clientOptions.rejectUnauthorized = credentials.rejectUnauthorized;
} }
return await connectAsync(clientOptions); return await new Promise((resolve, reject) => {
const client = connect(clientOptions);
const onConnect = () => {
client.removeListener('connect', onConnect);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
client.removeListener('error', onError);
resolve(client);
};
const onError = (error: Error) => {
client.removeListener('connect', onConnect);
client.removeListener('error', onError);
reject(new ApplicationError(error.message));
};
client.once('connect', onConnect);
client.once('error', onError);
});
}; };