All files / builtins/csv-lookup index.ts

100% Statements 88/88
100% Branches 16/16
100% Functions 21/21
100% Lines 85/85

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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248  3x   3x 3x 3x 3x     3x   3x               3x                 3x   3x 15x             15x 13x 13x 2x   11x               15x 13x 2x 1x         1x     11x 2x             15x 18x         15x 8x 1x   1x 11x 11x     1x     7x             15x 8x 1x     7x                 15x             8x   8x 1x   1x 3x     1x     7x   5x 2x   2x   3x 3x     2x     3x   3x         2x               15x 18x 54x     42x           15x 10x 10x           9x   1x 1x                   15x 14x 13x   13x 10x   9x   9x 9x 9x 27x 27x       9x   9x 1x     8x                   15x 14x 1x     13x                 13x           15x          
/* eslint-disable eqeqeq */
import {readFile} from 'fs/promises';
 
import axios from 'axios';
import {z} from 'zod';
import {parse} from 'csv-parse/sync';
import {ERRORS} from '@grnsft/if-core/utils';
import {ExecutePlugin, PluginParams} from '@grnsft/if-core/types';
 
import {validate} from '../../util/validations';
 
import {STRINGS} from '../../config';
 
const {
  FILE_FETCH_FAILED,
  FILE_READ_FAILED,
  MISSING_CSV_COLUMN,
  NO_QUERY_DATA,
  MISSING_GLOBAL_CONFIG,
} = STRINGS;
 
const {
  FetchingFileError,
  ReadFileError,
  MissingCSVColumnError,
  QueryDataNotFoundError,
  GlobalConfigError,
  CSVParseError,
} = ERRORS;
 
export const CSVLookup = (globalConfig: any): ExecutePlugin => {
  const metadata = {
    kind: 'execute',
  };
 
  /**
   * Checks if given string is URL.
   */
  const isURL = (filepath: string) => {
    try {
      new URL(filepath);
      return true;
    } catch (error) {
      return false;
    }
  };
 
  /**
   * Checks if given `filepath` is url, then tries to fetch it.
   * Otherwise tries to read file.
   */
  const retrieveFile = async (filepath: string) => {
    if (isURL(filepath)) {
      const {data} = await axios.get(filepath).catch(error => {
        throw new FetchingFileError(
          FILE_FETCH_FAILED(filepath, error.response.message)
        );
      });
 
      return data;
    }
 
    return readFile(filepath).catch(error => {
      throw new ReadFileError(FILE_READ_FAILED(filepath, error));
    });
  };
 
  /**
   * Checks if value is invalid: `undefined`, `null` or an empty string, then sets `nan` instead.
   */
  const setNanValue = (value: any) =>
    value == null || value === '' ? 'nan' : value;
 
  /**
   * Converts empty values to `nan`.
   */
  const nanifyEmptyValues = (object: any) => {
    if (typeof object === 'object') {
      const keys = Object.keys(object);
 
      keys.forEach(key => {
        const value = object[key];
        object[key] = setNanValue(value);
      });
 
      return object;
    }
 
    return setNanValue(object);
  };
 
  /**
   * If `field` is missing from `object`, then reject with error.
   * Otherwise nanify empty values and return data.
   */
  const fieldAccessor = (field: string, object: any) => {
    if (!(`${field}` in object)) {
      throw new MissingCSVColumnError(MISSING_CSV_COLUMN(field));
    }
 
    return nanifyEmptyValues(object[field]);
  };
 
  /**
   * 1. If output is anything, then removes query data from csv record to escape duplicates.
   * 2. Otherwise checks if it's a miltidimensional array, then grabs multiple fields ().
   * 3. If not, then returns single field.
   * 4. In case if it's string, then
   */
  const filterOutput = (
    dataFromCSV: any,
    params: {
      output: string | string[] | string[][];
      query: Record<string, any>;
    }
  ) => {
    const {output, query} = params;
 
    if (output === '*') {
      const keys = Object.keys(query);
 
      keys.forEach(key => {
        delete dataFromCSV[key];
      });
 
      return nanifyEmptyValues(dataFromCSV);
    }
 
    if (Array.isArray(output)) {
      /** Check if it's a multidimensional array. */
      if (Array.isArray(output[0])) {
        const result: any = {};
 
        output.forEach(outputField => {
          /** Check if there is no renaming request, then export as is */
          const outputTitle = outputField[1] || outputField[0];
          result[outputTitle] = fieldAccessor(outputField[0], dataFromCSV);
        });
 
        return result;
      }
 
      const outputTitle = output[1] || output[0];
 
      return {
        [outputTitle as string]: fieldAccessor(output[0], dataFromCSV),
      };
    }
 
    return {
      [output]: fieldAccessor(output, dataFromCSV),
    };
  };
 
  /**
   * Asserts CSV record with query data.
   */
  const withCriteria = (queryData: Record<string, any>) => (csvRecord: any) => {
    const ifMatchesCriteria = Object.keys(queryData).map(
      (key: string) => csvRecord[key] == queryData[key]
    );
 
    return ifMatchesCriteria.every(value => value === true);
  };
 
  /**
   * Parses CSV file.
   */
  const parseCSVFile = (file: string | Buffer) => {
    try {
      const parsedCSV: any[] = parse(file, {
        columns: true,
        skip_empty_lines: true,
        cast: true,
      });
 
      return parsedCSV;
    } catch (error: any) {
      console.error(error);
      throw new CSVParseError(error);
    }
  };
 
  /**
   * 1. Validates global config.
   * 2. Tries to retrieve given file (with url or local path).
   * 3. Parses given CSV.
   * 4. Filters requested information from CSV.
   */
  const execute = async (inputs: PluginParams[]) => {
    const safeGlobalConfig = validateGlobalConfig();
    const {filepath, query, output} = safeGlobalConfig;
 
    const file = await retrieveFile(filepath);
    const parsedCSV = parseCSVFile(file);
 
    return inputs.map(input => {
      /** Collects query values from input. */
      const queryData: any = {};
      const queryKeys = Object.keys(query);
      queryKeys.forEach(queryKey => {
        const queryValue = query[queryKey];
        queryData[queryKey] = input[queryValue];
      });
 
      /** Gets related data from CSV. */
      const relatedData = parsedCSV.find(withCriteria(queryData));
 
      if (!relatedData) {
        throw new QueryDataNotFoundError(NO_QUERY_DATA);
      }
 
      return {
        ...input,
        ...filterOutput(relatedData, {output, query}),
      };
    });
  };
 
  /**
   * Checks for `filepath`, `query` and `output` fields in global config.
   */
  const validateGlobalConfig = () => {
    if (!globalConfig) {
      throw new GlobalConfigError(MISSING_GLOBAL_CONFIG);
    }
 
    const globalConfigSchema = z.object({
      filepath: z.string(),
      query: z.record(z.string(), z.string()),
      output: z
        .string()
        .or(z.array(z.string()))
        .or(z.array(z.array(z.string()))),
    });
 
    return validate<z.infer<typeof globalConfigSchema>>(
      globalConfigSchema,
      globalConfig
    );
  };
 
  return {
    metadata,
    execute,
  };
};