js-waku/packages/discovery/src/dns/dns_over_https.ts

59 lines
1.4 KiB
TypeScript
Raw Normal View History

import type { DnsClient } from "@waku/interfaces";
import { Logger } from "@waku/utils";
import { bytesToUtf8 } from "@waku/utils/bytes";
import DnsOverHttpResolver from "dns-over-http-resolver";
2022-01-13 11:33:26 +11:00
const log = new Logger("dns-over-https");
2022-01-13 11:33:26 +11:00
export class DnsOverHttps implements DnsClient {
/**
* Create new Dns-Over-Http DNS client.
*
* @throws {code: string} If DNS query fails.
*/
public static async create(): Promise<DnsOverHttps> {
return new DnsOverHttps();
}
private constructor(private resolver = new DnsOverHttpResolver()) {}
2022-01-13 11:33:26 +11:00
/**
* Resolves a TXT record
*
* @param domain The domain name
*
2022-07-19 15:43:35 +10:00
* @throws if the query fails
*/
public async resolveTXT(domain: string): Promise<string[]> {
2022-07-19 15:43:35 +10:00
let answers;
try {
answers = await this.resolver.resolveTxt(domain);
2022-07-19 15:43:35 +10:00
} catch (error) {
log.error("query failed: ", error);
2022-07-19 15:43:35 +10:00
throw new Error("DNS query failed");
}
2022-01-13 11:33:26 +11:00
2022-07-19 15:43:35 +10:00
if (!answers) throw new Error(`Could not resolve ${domain}`);
2022-01-13 11:33:26 +11:00
const result: string[] = [];
answers.forEach((d) => {
2022-02-04 14:12:00 +11:00
if (typeof d === "string") {
2022-01-13 11:33:26 +11:00
result.push(d);
} else if (Array.isArray(d)) {
d.forEach((sd) => {
2022-02-04 14:12:00 +11:00
if (typeof sd === "string") {
2022-01-13 11:33:26 +11:00
result.push(sd);
} else {
2022-02-16 14:08:48 +11:00
result.push(bytesToUtf8(sd));
2022-01-13 11:33:26 +11:00
}
});
} else {
2022-02-16 14:08:48 +11:00
result.push(bytesToUtf8(d));
2022-01-13 11:33:26 +11:00
}
});
return result;
}
}