js-waku/packages/discovery/src/dns/dns_over_https.ts
fryorcraken edfb56243d
doc: build first to avoid not found deps issues (#2307)
* doc: build first to avoid not found deps issues

* fix: Remove XMLHttpRequest usage

XMLHttpRequest API is deprecated and not available in browser extensions.

Replace the culprit dependency with a more modern one.

Some options are removed. The assumption is that nobody uses them. It can always be added if a developer wants the flexibility.

* test: simplify test

The test focus on testing DNS Discovery, there is no need to also have a nwaku local node for bootstrap.

Bootstrap on nwaku local node is used in many other tests.
2025-03-19 09:43:41 +01:00

59 lines
1.4 KiB
TypeScript

import type { DnsClient } from "@waku/interfaces";
import { Logger } from "@waku/utils";
import { bytesToUtf8 } from "@waku/utils/bytes";
import DnsOverHttpResolver from "dns-over-http-resolver";
const log = new Logger("dns-over-https");
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()) {}
/**
* Resolves a TXT record
*
* @param domain The domain name
*
* @throws if the query fails
*/
public async resolveTXT(domain: string): Promise<string[]> {
let answers;
try {
answers = await this.resolver.resolveTxt(domain);
} catch (error) {
log.error("query failed: ", error);
throw new Error("DNS query failed");
}
if (!answers) throw new Error(`Could not resolve ${domain}`);
const result: string[] = [];
answers.forEach((d) => {
if (typeof d === "string") {
result.push(d);
} else if (Array.isArray(d)) {
d.forEach((sd) => {
if (typeof sd === "string") {
result.push(sd);
} else {
result.push(bytesToUtf8(sd));
}
});
} else {
result.push(bytesToUtf8(d));
}
});
return result;
}
}