All files / utils/backend validation.ts

97.57% Statements 161/165
87.01% Branches 67/77
100% Functions 1/1
97.57% Lines 161/165

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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197  1x   1x   1x 74x 74x 74x 74x 74x 74x     74x 74x 74x 74x 70x 70x 74x 5x 5x 5x 5x 5x     69x 274x     274x     274x 119x 11x 11x 119x 119x     274x 5x 150x 274x 274x     274x 89x 89x 89x 85x 82x 89x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 79x 79x     273x 41x 41x 41x 37x 36x 35x 41x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 34x 34x     274x 13x 13x 13x 12x 12x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x     274x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 6x 6x 6x 6x   6x 4x 6x       6x 1x 1x 1x 1x     274x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x     274x 1x 1x 1x     134x 69x   74x 14x 14x 14x 14x 14x   55x 55x 55x 55x 55x  
import { Validator } from '@/types/backend/validation';
import { getLogger } from '@/utils/common/logger';
 
const logger = getLogger('stack/utils/validation');
 
export function validateObject<T extends object>(
  obj: any, // eslint-disable-line @typescript-eslint/no-explicit-any
  validator: Validator<T>,
  useMultiValue: boolean = false
): [T | null, string[] ] {
  logger.trace('validateObject', ...arguments);
  const newObj: Partial<T> = {};
 
  // Validate the object
  const objKeys = Object.keys(validator) as (keyof typeof validator)[];
  const badKeys: string[] = [];
  if (
    typeof obj !== 'object' ||
    Array.isArray(obj) ||
    obj === null
  ) {
    return [
      null,
      objKeys as string[],
    ];
  }
 
  // Loop over the keys
  objKeys.forEach(key => {
    if (typeof key !== 'string') {
      return;
    }
    const config = validator[key];
 
    // If the key is undefined, show an error if it is required
    if (typeof obj[key] === 'undefined') {
      if (config.required) {
        badKeys.push(key);
      }
      return;
    }
 
    // Validate using the different types
    const rawValue = useMultiValue && Array.isArray(obj[key]) && obj[key].length === 1 && typeof config.types.array === 'undefined'
      ? obj[key][0]
      : obj[key];
    const value = config.parse ? config.parse(rawValue) : rawValue;
    let foundType = false;
 
    // Validate strings
    if (typeof value === 'string') {
      const conf = config.types.string;
      if (
        !conf ||
        (conf.regex && !conf.regex.test(value)) ||
        (conf.exact && !conf.exact.includes(value as typeof conf.exact[number]))
      ) {
        logger.error(
          `Failed to validate ${String(key)} as string`,
          obj[key],
          value,
          conf,
          conf?.regex && !conf.regex.test(value),
          conf?.exact && !conf.exact.includes(value as typeof conf.exact[number])
        );
        badKeys.push(key);
        return;
      }
      foundType = true;
    }
 
    // Validate numbers
    if (typeof value === 'number') {
      const conf = config.types.number;
      if (
        !conf ||
        Number.isNaN(value) ||
        (conf.regex && !conf.regex.test(value.toString())) ||
        (conf.exact && !conf.exact.includes(value as typeof conf.exact[number]))
      ) {
        logger.error(
          `Failed to validate ${String(key)} as number`,
          obj[key],
          value,
          conf,
          Number.isNaN(value),
          conf?.regex && !conf.regex.test(value.toString()),
          conf?.exact && !conf.exact.includes(value as typeof conf.exact[number])
        );
        badKeys.push(key);
        return;
      }
      foundType = true;
    }
 
    // Validate booleans
    if (typeof value === 'boolean') {
      const conf = config.types.boolean;
      if (
        !conf ||
        (conf.regex && !conf.regex.test(value.toString())) ||
        (conf.exact && !conf.exact.includes(value as typeof conf.exact[number]))
      ) {
        logger.error(
          `Failed to validate ${String(key)} as boolean`,
          obj[key],
          value,
          conf,
          conf?.regex && !conf.regex.test(value.toString()),
          conf?.exact && !conf.exact.includes(value as typeof conf.exact[number])
        );
        badKeys.push(key);
        return;
      }
      foundType = true;
    }
 
    // Validate arrays
    if (Array.isArray(value)) {
      const conf = config.types.array;
      if (
        !conf ||
        (conf.regex && value.some(v => !conf.regex?.test(v.toString()))) ||
        (conf.exact && value.some(v => !conf.exact?.includes(v)))
      ) {
        logger.error(
          `Failed to validate ${String(key)} as boolean`,
          obj[key],
          value,
          conf,
          conf?.regex && value.some(v => !conf.regex?.test(v.toString())),
          conf?.exact && value.some(v => !conf.exact?.includes(v))
        );
        badKeys.push(key);
        return;
      }
 
      // Validate each array item
      if ('items' in conf) {
        const itemConf = conf.items as Validator<T[typeof key]>;
        value.map((item, idx) => {
          const [
            itemReal,
            itemErrors,
          ] = validateObject(item, itemConf);
 
          if (itemErrors.length > 0) {
            badKeys.push(...itemErrors.map(err => `${key}-${idx}-${err}`));
          } else if (itemReal === null) {
            badKeys.push(`${key}-${idx}-null`);
          }
 
          return itemReal;
        });
      }
      foundType = true;
    }
 
    // Validate null values
    if (value === null) {
      const conf = config.types.null;
      if (!conf) {
        logger.error(
          `Failed to validate ${String(key)} as null`,
          obj[key],
          value,
          conf
        );
        badKeys.push(key);
        return;
      }
      foundType = true;
    }
 
    // If it isn't a valid type
    if (!foundType) {
      badKeys.push(key);
      return;
    }
 
    // Add the key to the object
    newObj[key] = value;
  });
 
  if (badKeys.length > 0) {
    return [
      null,
      badKeys,
    ];
  }
 
  return [
    newObj as T,
    [],
  ];
}