All files / src/command config.js

93.93% Statements 31/33
100% Branches 12/12
100% Functions 6/6
93.93% Lines 31/33

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135    3x         3x                                       12x                                 6x 6x 6x   1x                   2x   43x 1x   42x   42x                   4x   4x   4x 4x 4x                                               4x 4x   1x   1x 1x   1x 1x 1x   1x 1x 1x   1x 1x 1x                      
import { interopImportCJSDefault } from 'node-cjs-interop';
import asyncValidator from 'async-validator';
const Schema = interopImportCJSDefault(asyncValidator);
import BaseSubCommand from './baseSubCommand.js';
import { configCommandParameters, configCommandUsage, commonGlobalOptionValidatorDesc } from '../utils/constants.js';
import { logger } from '../utils/myLogger.js';
 
const configCommandValidatorDesc = {
  ...commonGlobalOptionValidatorDesc,
  endpoint: {
    ...commonGlobalOptionValidatorDesc.endpoint,
    required: false
  }
};
 
/**
 * @typedef {import('commander').Command} Command
 * @typedef {import('async-validator').Rules} Rules
 * @typedef {import('async-validator').Values} Values
 * @typedef {import('../../types/rc/index.js').default} Registry
 */
class ConfigCommand extends BaseSubCommand {
  /**
   * Constructs a new ConfigCommand instance.
   * @param {Registry} rc - The registry instance.
   */
  constructor(rc) {
    super(
      'config',
      configCommandParameters,
      'Get, set, delete or list aelf-command config',
      [],
      configCommandUsage,
      rc,
      configCommandValidatorDesc
    );
  }
  /**
   * Validates parameters based on the provided rules.
   * @param {Rules} rule - The validation rules.
   * @param {Values} parameters - The parameters to validate.
   * @returns {Promise<void>} A promise that resolves when the validation is complete.
   */
  async validateParameters(rule, parameters) {
    const validator = new Schema(rule);
    try {
      await validator.validate(parameters);
    } catch (e) {
      this.handleUniOptionsError(e);
    }
  }
 
  /**
   * Handles the list operation and returns the processed content as a string.
   * @param {any} content - The content to process.
   * @returns {string} The processed content.
   */
  handleList(content) {
    return Object.entries(content)
      .filter(([, value]) => {
        if (value === '' || value === undefined || value === null) {
          return false;
        }
        return true;
      })
      .map(([key, value]) => `${key}=${value}\n`)
      .join('');
  }
  /**
   * Executes the command.
   * @param {Command} commander - The commander instance.
   * @param {...any} args - Additional arguments.
   * @returns {Promise<void>} A promise that resolves when the command execution is complete.
   */
  async run(commander, ...args) {
    this.setCustomPrompts(true);
    // @ts-ignore
    const { subOptions } = await super.run(commander, ...args);
    // todo: specified which .aelfrc file to read or write
    const { flag, key, value } = subOptions;
    try {
      await this.validateParameters(
        {
          flag: {
            type: 'enum',
            enum: ['set', 'get', 'delete', 'list'],
            required: true,
            message: 'Flag must one of set, get, list, delete'
          },
          key: {
            type: 'string',
            required: ['get', 'set', 'delete'].includes(flag),
            message: 'You need to enter the <key>'
          },
          value: {
            type: 'string',
            required: flag === 'set',
            message: 'You need to enter the correct <value> for config set',
            // The follow validator will get the pattern if the [key] in commonGlobalOptionValidatorDesc.
            // At the same time avoid an error if [key] is not in.
            pattern: (key in commonGlobalOptionValidatorDesc && commonGlobalOptionValidatorDesc[key].pattern) || null
          }
        },
        subOptions
      );
      let result = null;
      switch (flag) {
        case 'get':
          result = this.rc.getOption(key);
          // @ts-ignore
          logger.info(result);
          break;
        case 'set':
          this.rc.saveOption(key, value);
          this.oraInstance.succeed('Succeed!');
          break;
        case 'list':
          result = this.rc.getFileConfigs();
          console.log(`\n${this.handleList(result)}`);
          break;
        case 'delete':
          result = this.rc.deleteConfig(key);
          this.oraInstance.succeed('Succeed!');
          break;
      }
    } catch (e) {
      this.oraInstance.fail('Failed!');
      // @ts-ignore
      logger.error(e);
    }
  }
}
 
export default ConfigCommand;