All files / if-run/builtins/copy-param index.ts

100% Statements 27/27
100% Branches 11/11
100% Functions 4/4
100% Lines 27/27

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 735x   5x         5x   5x   5x   5x 5x               5x   7x 1x     6x           6x 6x       6x   6x     6x 6x     6x   6x     5x 5x 5x   5x 5x   5x 5x     5x                
import {z} from 'zod';
 
import {
  ERRORS,
  getParameterFromArithmeticExpression,
} from '@grnsft/if-core/utils';
import {ConfigParams, PluginParams} from '@grnsft/if-core/types';
import {PluginFactory} from '@grnsft/if-core/interfaces';
 
import {validate} from '../../../common/util/validations';
 
import {STRINGS} from '../../config';
 
const {ConfigError} = ERRORS;
const {MISSING_CONFIG} = STRINGS;
 
/**
 * keep-existing: true/false (whether to remove the parameter you are copying from)
 * from-param: the parameter you are copying from (e.g. cpu/name)
 * to-field: the parameter you are copying to (e.g. cpu/processor-name)
 */
 
export const Copy = PluginFactory({
  configValidation: (config: ConfigParams) => {
    if (!config || !Object.keys(config)?.length) {
      throw new ConfigError(MISSING_CONFIG);
    }
 
    const configSchema = z.object({
      'keep-existing': z.boolean(),
      from: z.string().min(1),
      to: z.string().min(1),
    });
 
    const extractedFrom = getParameterFromArithmeticExpression(config.from);
    const updatedConfig = config['keep-existing']
      ? config
      : {...config, 'pure-from': extractedFrom};
 
    validate<z.infer<typeof configSchema>>(configSchema, updatedConfig);
 
    return updatedConfig;
  },
  inputValidation: (input: PluginParams, config: ConfigParams) => {
    const from = config.from;
    const inputData = {
      [from]: input[from],
    };
    const validationSchema = z.record(z.string(), z.string().or(z.number()));
 
    return validate(validationSchema, inputData);
  },
  implementation: async (inputs: PluginParams[], config: ConfigParams) => {
    const keepExisting = config['keep-existing'] === true;
    const from = config['from'];
    const to = config['to'];
 
    return inputs.map(input => {
      const outputValue = !isNaN(from) ? from : input[from];
 
      if (input[from] || (!isNaN(from) && !keepExisting)) {
        delete input[config['pure-from']];
      }
 
      return {
        ...input,
        [to]: outputValue,
      };
    });
  },
  allowArithmeticExpressions: ['from'],
});