all files / src/ ConfigClusterResolver.js

100% Statements 50/50
94.44% Branches 34/36
100% Functions 8/8
100% Lines 33/33
1 statement, 2 branches Ignored     
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 44 45 46 47 48 49 50 51 52 53           60× 60× 60×     29× 29×   29×     60× 60× 60× 60× 60× 60× 60×         60× 55× 55×   60×     60× 60×   58×      
import Logger from './Logger';
 
/*
  Locates a Eureka host using static configuration. Configuration can either be
  done using a simple host and port, or a map of serviceUrls.
 */
export default class ConfigClusterResolver {
  constructor(config, logger) {
    this.logger = logger || new Logger();
    this.config = config;
    this.serviceUrls = this.buildServiceUrls();
  }
 
  resolveEurekaUrl(callback, retryAttempt = 0) {
    if (this.serviceUrls.length > 1 && retryAttempt > 0) {
      this.serviceUrls.push(this.serviceUrls.shift());
    }
    callback(null, this.serviceUrls[0]);
  }
 
  buildServiceUrls() {
    const { host, port, servicePath, ssl,
      serviceUrls, preferSameZone } = this.config.eureka;
    const { metadata } = this.config.instance.dataCenterInfo;
    const instanceZone = metadata ? metadata['availability-zone'] : undefined;
    const urls = [];
    const zones = this.getAvailabilityZones();
    if (serviceUrls) {
      zones.forEach((zone) => {
        if (EserviceUrls[zone]) {
          if (preferSameZone && instanceZone && instanceZone === zone) {
            urls.unshift(...serviceUrls[zone]);
          }
          urls.push(...serviceUrls[zone]);
        }
      });
    }
    if (!urls.length) {
      const protocol = ssl ? 'https' : 'http';
      urls.push(`${protocol}://${host}:${port}${servicePath}`);
    }
    return urls;
  }
 
  getAvailabilityZones() {
    const { ec2Region, availabilityZones } = this.config.eureka;
    if (ec2Region && availabilityZones && availabilityZones[ec2Region]) {
      return availabilityZones[ec2Region];
    }
    return ['default'];
  }
}