All files / src/models node-dns-resolver.js

53.48% Statements 23/43
100% Branches 1/1
0% Functions 0/3
53.48% Lines 23/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44193x 193x 193x 193x     193x 193x 193x 193x 193x 193x 193x 193x 193x                   193x 193x 193x 193x 193x 193x 193x 193x 193x                   193x  
import { Resolver } from 'node:dns/promises';
 
export class DnsResolver {
  constructor() {
    this._resolver = new Resolver();
  }
 
  /**
   * Resolves A records for the given hostname.
   *
   * @async
   * @param {string} hostname - The hostname to resolve A records for.
   * @returns {Promise<string[]>} A promise that resolves to an array of IP addresses, or an empty array if not found or an error occurs.
   */
  resolveA(hostname) {
    return this._resolver.resolve4(hostname).catch((error) => {
      switch (error.code) {
        case 'ENOTFOUND':
        case 'ENODATA':
          return [];
      }
      throw new Error(`Could not resolve DNS for ${hostname}. Caused by: ${error.message}`);
    });
  }
 
  /**
   * Resolves CNAME records for the given hostname.
   *
   * @async
   * @param {string} hostname - The hostname to resolve CNAME records for.
   * @returns {Promise<string|null>} A promise that resolves to the CNAME record if found, or null if not found or an error occurs.
   */
  resolveCname(hostname) {
    return this._resolver.resolveCname(hostname).catch((error) => {
      switch (error.code) {
        case 'ENOTFOUND':
        case 'ENODATA':
          return null;
      }
      throw new Error(`Could not resolve DNS for ${hostname}. Caused by: ${error.message}`);
    });
  }
}