1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00
Files
checktheroads-hyperglass/hyperglass/ui/hooks/use-dns-query.ts

62 lines
1.6 KiB
TypeScript
Raw Normal View History

import { useQuery } from '@tanstack/react-query';
import { useConfig } from '~/context';
import { fetchWithTimeout } from '~/util';
import type {
QueryFunction,
QueryFunctionContext,
QueryObserverResult,
} from '@tanstack/react-query';
import type { DnsOverHttps } from '~/types';
2021-12-18 23:45:06 -07:00
type DNSQueryKey = [string, { target: string | null; family: 4 | 6 }];
2020-12-31 23:09:54 -07:00
/**
* Perform a DNS over HTTPS query using the application/dns-json MIME type.
*/
2021-05-29 23:30:38 -07:00
const query: QueryFunction<DnsOverHttps.Response, DNSQueryKey> = async (
ctx: QueryFunctionContext<DNSQueryKey>,
) => {
const [url, { target, family }] = ctx.queryKey;
const controller = new AbortController();
2024-02-27 17:44:19 -05:00
let json = undefined;
const type = family === 4 ? 'A' : family === 6 ? 'AAAA' : '';
if (url !== null) {
const res = await fetchWithTimeout(
`${url}?name=${target}&type=${type}`,
{
headers: { accept: 'application/dns-json' },
mode: 'cors',
},
5000,
controller,
);
json = await res.json();
}
return json;
2021-05-29 23:30:38 -07:00
};
2020-12-31 23:09:54 -07:00
/**
* Query the configured DNS over HTTPS provider for the provided target. If `family` is `4`, only
* an A record will be queried. If `family` is `6`, only a AAAA record will be queried.
*/
export function useDNSQuery(
2021-12-20 10:58:38 -07:00
/** Hostname for DNS query. */
2020-12-31 23:09:54 -07:00
target: string | null,
2021-12-20 10:58:38 -07:00
/** Address family, e.g. IPv4 or IPv6. */
2020-12-31 23:09:54 -07:00
family: 4 | 6,
2021-01-03 23:51:09 -07:00
): QueryObserverResult<DnsOverHttps.Response> {
const { cache, web } = useConfig();
2021-01-10 01:14:57 -07:00
2021-05-29 23:30:38 -07:00
return useQuery<DnsOverHttps.Response, unknown, DnsOverHttps.Response, DNSQueryKey>({
queryKey: [web.dnsProvider.url, { target, family }],
2021-05-29 23:30:38 -07:00
queryFn: query,
cacheTime: cache.timeout * 1000,
});
}