services/domain-service.js

/**
 * AngularJS Service that figures out the subdomain.
 *
 * @module domainService
 * @see https://docs.angularjs.org/api/ng/type/angular.Module#service
 */
angular.module('tgaApp').service('domainService', ['$location', 'envService',
  function domainService($location, envService) {
    const serverAddress = envService.read('serverAddress');
    const forceDomain = envService.read('forceDomain');
    const host = $location.host();
    let base = host;
    let domain = null;

    if (host.indexOf('.') >= 2) {
      const parts = host.split('.');
      domain = parts.shift();
      base = parts.join('.');
    }

    if (forceDomain) {
      domain = forceDomain;
    }

    /**
     * The URL to the API root (e.g. `https://api.thetrainingarcade.com/api/v5/`).
     *
     * @static
     * @readonly
     * @member {string} api
     */
    Object.defineProperty(this, 'api', {
      value: serverAddress,
    });

    /**
     * The base hostname.
     * Typically this is the full hostname with the leftmost segment removed.
     *
     * @static
     * @readonly
     * @member {string} base
     */
    Object.defineProperty(this, 'base', {
      value: base,
    });

    /**
     * The domain identifier.
     * Typically this is the leftmost segment of the full hostname, but may be
     * overriden with the `forceDomain` environment variable.
     *
     * @static
     * @readonly
     * @member {?string} domain
     */
    Object.defineProperty(this, 'domain', {
      value: domain,
    });
  },
]);