All files / src/models domain.js

23.18% Statements 16/69
100% Branches 1/1
0% Functions 0/4
23.18% Lines 16/69

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                       193x 193x                     193x 193x                       193x 193x                            
import {
  getAllDomains,
  getFavouriteDomain as getFavouriteDomainWithError,
} from '@clevercloud/client/esm/api/v2/application.js';
import _ from 'lodash';
import { parse as parseDomain } from 'tldts';
import { Logger } from '../logger.js';
import { sendToApi } from './send-to-api.js';
 
export async function getBest(appId, orgaId) {
  Logger.debug('Trying to get the favourite vhost for ' + appId);
  return getFavouriteDomainWithError({ id: orgaId, appId })
    .then(sendToApi)
    .catch(async (e) => {
      if (e.response.status !== 404) {
        throw e;
      }

      Logger.debug('No favourite vhost defined for ' + appId + ', selecting the best one');
      const allDomains = await getAllDomains({ id: orgaId, appId }).then(sendToApi);
      const result = selectBest(allDomains);

      if (result == null) {
        throw new Error("Couldn't find a domain name");
      }

      return result;
    });
}
 
export function selectBest(vhosts) {
  const customVhost = _.find(vhosts, (vhost) => {
    return !vhost.fqdn.endsWith('.cleverapps.io');
  });
  const withoutDefaultDomain = _.find(vhosts, (vhost) => {
    return !vhost.fqdn.match(
      /^app-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.cleverapps\.io$/,
    );
  });
  return customVhost || withoutDefaultDomain || vhosts[0];
}
 
export function getFavouriteDomain({ ownerId, appId }) {
  return getFavouriteDomainWithError({ id: ownerId, appId })
    .then(sendToApi)
    .then(({ fqdn }) => fqdn)
    .catch((error) => {
      if (error.id === 4021) {
        // No favourite vhost
        return null;
      }
      throw error;
    });
}
 
export function getDomainObject(domainWithPathPrefix, favouriteDomain) {
  const parsed = parseDomain(domainWithPathPrefix, { validateHostname: false });
  return {
    domainWithPathPrefix,
    domain: parsed.domain,
    domainWithoutSuffix: parsed.domainWithoutSuffix,
    hostname: parsed.hostname,
    publicSuffix: parsed.publicSuffix,
    subdomain: parsed.subdomain,
    isApex: parsed.subdomain === '',
    pathPrefix: new URL('https://' + domainWithPathPrefix).pathname,
    isFavourite: domainWithPathPrefix === favouriteDomain,
  };
}