martes, 31 de agosto de 2021

querySrv ENODATA checking a Mongo SRV record using Node

The Mongo driver prefix the "hostname" with "_mongodb._tcp.".

Reference https://github.com/mongodb/node-mongodb-native/blob/e69d9925713ede3bd80d7d23a6df60c6dd4542ef/src/connection_string.ts#L78

function getMongoSrvHostnameFromDbConnectionString(dbConnectionString: string) {
const startIndex = dbConnectionString.indexOf('@') + 1;
const endIndex = dbConnectionString.indexOf('/', startIndex);
const dbHostname = dbConnectionString.substring(startIndex, endIndex);
// Ref: https://github.com/mongodb/node-mongodb-native/blob/e69d9925713ede3bd80d7d23a6df60c6dd4542ef/src/connection_string.ts#L78
return `_mongodb._tcp.${dbHostname}`;
}

async function resolveSrvHostnamesOrError(
hostname: string,
): Promise<string[] | string> {
const resolveSrv = util.promisify(dns.resolveSrv);
const lookup = util.promisify(dns.lookup);
let ipsOrError: string[] | string = null;
try {
const resolvedHostnames = await resolveSrv(hostname);
const resolvedAddresses = await Promise.all(
resolvedHostnames.map(
async (resolvedHostname) => await lookup(resolvedHostname.name),
),
);

return await Promise.all(
resolvedAddresses.map(
async (resolvedAddress) => (await resolvedAddress).address,
),
);
} catch (err) {
console.log(err);
const e: Error = err;
ipsOrError = e.message;
return ipsOrError;
}
}

No hay comentarios: