export async function convertIotHubToEventHubsConnectionString()

in public/utils/connStringHelper.ts [57:126]


export async function convertIotHubToEventHubsConnectionString(connectionString: string): Promise<string> {
    const { HostName, SharedAccessKeyName, SharedAccessKey } = parseConnectionString<{
        HostName: string;
        SharedAccessKeyName: string;
        SharedAccessKey: string;
    }>(connectionString);

    // Verify that the required info is in the connection string.
    if (!HostName || !SharedAccessKey || !SharedAccessKeyName) {
        throw new Error(`Invalid IotHub connection string.`);
    }

    //Extract the IotHub name from the hostname.
    const [iotHubName] = HostName.split(".");

    if (!iotHubName) {
        throw new Error(`Unable to extract the IotHub name from the connection string.`);
    }

    // Generate a token to authenticate to the service.
    // The code for generateSasToken can be found at https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security#security-tokens
    const token = generateSasToken(
        `${HostName}/messages/events`,
        SharedAccessKey,
        SharedAccessKeyName,
        5 // token expires in 5 minutes
    );

    const connection = new Connection({
        transport: "tls",
        host: HostName,
        hostname: HostName,
        username: `${SharedAccessKeyName}@sas.root.${iotHubName}`,
        port: 5671,
        reconnect: false,
        password: token
    });
    await connection.open();

    // Create the receiver that will trigger a redirect error.
    const receiver = await connection.createReceiver({
        source: { address: `amqps://${HostName}/messages/events/$management` },
    });

    return new Promise((resolve, reject) => {
        receiver.on(ReceiverEvents.receiverError, (context) => {
            const error = context.receiver && context.receiver.error;
            if (isAmqpError(error) && error.condition === AMQPError.LinkRedirectError && error.info) {
            const hostname = error.info.hostname;
            // an example: "amqps://iothub.test-1234.servicebus.windows.net:5671/hub-name/$management"
            const iotAddress = error.info.address;
            const regex = /:\d+\/(.*)\/\$management/i;
            const regexResults = regex.exec(iotAddress);
            if (!hostname || !regexResults) {
                reject(error);
            } else {
                const eventHubName = regexResults[1];
                resolve(
                `Endpoint=sb://${hostname}/;EntityPath=${eventHubName};SharedAccessKeyName=${SharedAccessKeyName};SharedAccessKey=${SharedAccessKey}`
                );
            }
            } else {
                reject(error);
            }
            connection.close().catch(() => {
            /* ignore error */
            });
        });
    });
}