All files camelify.ts

96.15% Statements 25/26
87.5% Branches 7/8
100% Functions 8/8
95.83% Lines 23/24
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 551x 1x   1x               1x 35x         1x 7x       46x   1x 3x 35x   35x 19x     16x 5x     11x 11x 11x             3x     1x 3x 14x     1x  
import { constTrue, not, Predicate } from "fp-ts/lib/function";
import { fromNullable } from "fp-ts/lib/Option";
import { mixed } from "io-ts";
import { camelCase, fromPairs, isArray, isDate, isObject as _isObject, toPairs } from "lodash";
import { RowTransformer } from "../types";
 
export interface CamelifyOptions {
  exclude: Predicate<string>;
  keyMapper: (s: string) => string;
}
 
const isMappable: Predicate<mixed> = x =>
  fromNullable(x)
    .filter(isObject)
    .filter(not(isDate))
    .fold(false, constTrue);
 
const defaultOptions: CamelifyOptions = {
  exclude: (k: string) => k.startsWith("_"),
  keyMapper: camelCase,
};
 
const isObject = (x: mixed): x is object => _isObject(x);
 
const transform = (options: CamelifyOptions) => {
  const transformer = (x: mixed): mixed => {
    const { exclude, keyMapper } = options;
 
    if (!isMappable(x)) {
      return x;
    }
 
    if (isArray(x)) {
      return x.map(transformer);
    }
 
    Eif (isObject(x)) {
      return {
        ...fromPairs(toPairs(x).map(([k, v]) => [exclude(k) ? k : keyMapper(k), transformer(v)])),
      };
    }
 
    return x;
  };
 
  return transformer;
};
 
export const makeCamelCaser = (options?: Partial<CamelifyOptions>) => {
  const transformer = transform({ ...defaultOptions, ...options });
  return (xs: mixed[]): mixed[] => xs.map(transformer);
};
 
export const defaultCamelCaser: RowTransformer = makeCamelCaser();