All files Field.ts

100% Statements 21/21
100% Branches 6/6
100% Functions 6/6
100% Lines 18/18
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 371x 1x   1x   1x         14x 14x 14x     25x 25x   24x 20x 4x       4x 4x     1x 1x   1x     25x    
import { nonEmptyArray } from 'fp-ts/lib/NonEmptyArray';
import * as ValidationFn from 'fp-ts/lib/Validation';
 
import Decoder, { Decoded } from './Decoder';
 
export default class Field<a> extends Decoder<a> {
  private decoder: Decoder<a>;
  private field: string;
 
  constructor(field: string, decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
    this.field = field;
  }
 
  public run(valueObject: unknown): Decoded<a> {
    if (isObject(valueObject)) {
 
      if (this.field in valueObject) {
        return this.decoder.run(valueObject[this.field]).mapFailure(
          (errors) => errors.map((error) => `${error} at key "${this.field}"`),
        );
      }
 
      const noFieldMsg = `Object missing value at key "${this.field}"`;
      return ValidationFn.failure(nonEmptyArray.of(noFieldMsg));
    }
 
    const notObjectMsg = `Value must be a object, found "${typeof valueObject}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(notObjectMsg));
  }
}
 
function isObject(value: unknown): value is { [prop: string]: unknown } {
  return typeof value === 'object';
}