All files / utils checkPackage.util.ts

19.04% Statements 4/21
0% Branches 0/6
0% Functions 0/7
21.05% Lines 4/19

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 70 714x                     4x                   4x                                                               4x                                  
import { Logger } from '@nestjs/common/services/logger.service';
 
/**
 * Generates the string which packages are missing and
 * how to install them
 *
 * @param name The name of the packages
 * @param reason The reason why these packages are important
 *
 * @internal
 */
const MISSING_REQUIRED_DEPENDENCY = (names: string[], reason: string): string =>
  `The "${names.join('", "')}" package${
    names.length > 1 ? 's are' : ' is'
  } missing. Please, make sure to install the librar${
    names.length > 1 ? 'ies' : 'y'
  } ($ npm install ${names.join(' ')}) to take advantage of ${reason}.`;
 
/**
 * @internal
 */
const logger = new Logger('PackageLoader');
 
/**
 * Loads an optional module
 *
 * @param module The module name
 * @internal
 *
 * @returns {T | null} The module or null if has not found
 */
function optional<T = any>(module: string): T | null {
  try {
    Iif (module[0] in { '.': 1 }) {
      module = process.cwd() + module.substring(1);
    }
    return require(`${module}`);
  } catch (err) {}
  return null;
}
 
/**
 * Checks if the given packages are available and logs using the Nest Logger
 * which packages are not available
 * @param packageNames The package names
 * @param reason The reason why these packages are important
 *
 * @internal
 *
 * @example
 * //  The "no_package" package is missing. Please, make sure to install the library ($ npm install no_package) to take advantage of TEST.
 * checkPackages(['process', 'no_package'], 'TEST')
 */
export function checkPackages(packageNames: string[], reason: string): any[] {
  const packages = packageNames.map((packageName, index) => ({
    pkg: optional(packageName),
    index,
  }));
 
  const missingDependenciesNames = packages
    .filter((pkg) => pkg.pkg === null)
    .map((pkg) => packageNames[pkg.index]);
 
  Iif (missingDependenciesNames.length) {
    logger.error(MISSING_REQUIRED_DEPENDENCY(missingDependenciesNames, reason));
    Logger.flush();
    process.exit(1);
  }
  return packages.map((pkg) => pkg.pkg);
}