All files index.ts

100% Statements 237/237
100% Branches 46/46
100% Functions 99/99
100% Lines 211/211
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421    1x   1x   1x   1x 1x 5x     1x 12x     1x 6x     1x 25x     1x 4x     1x 13x     1x 4x     1x 7x     1x 1x     1x           1x     1x 2x 2x 2x 1x     1x           1x 9x     1x 6x         6x     1x 16x     1x 7x     1x 14x     1x 3x     1x 1x     1x 1x   1x       1x         5x 5x 5x     5x 5x   4x   1x   1x       12x 12x     12x 12x 7x 7x   7x   3x   3x 1x 2x     4x         5x 5x   1x   1x 1x 19x 11x     8x 8x   1x   1x       4x 4x     1x 4x   1x   1x         13x 13x 13x     54x 54x 53x 40x   13x     13x 13x     1x 1x   1x   1x         4x 4x 4x     4x 4x 3x 2x   1x     1x 1x     1x 1x   1x   1x         7x 7x 7x     1x 6x   1x   1x           1x 1x 1x 1x     1x 4x 4x 4x   4x 2x 1x 1x   2x 1x 1x       1x   1x                       1x 1x 1x 1x 1x     1x 8x 8x 8x 8x   8x 4x 2x 1x 1x   2x 1x 1x     4x 2x 1x 1x   2x 1x 1x         1x   1x       9x 9x     1x 10x 3x     7x 7x   1x   1x 1x 26x 16x     10x 10x   1x   1x       7x 7x     1x 9x   9x 2x     7x 9x 1x     8x     1x   1x 1x 17x 9x     8x 8x   1x   1x       3x 3x     1x 3x   1x   1x 1x 1x   1x     16x       54x    
/* tslint:disable:max-classes-per-file */
 
import { NonEmptyArray, nonEmptyArray } from 'fp-ts/lib/NonEmptyArray';
import { Option } from 'fp-ts/lib/Option';
import * as OptionFn from 'fp-ts/lib/Option';
import { Validation } from 'fp-ts/lib/Validation';
import * as ValidationFn from 'fp-ts/lib/Validation';
 
export default class Decoder<a> {
  public static andThen<a, b>(decoderFn: (value: a) => Decoder<b>, decoder: Decoder<a>): Decoder<b> {
    return new AndThenD(decoderFn, decoder);
  }
 
  public static array<a>(decoder: Decoder<a>): Decoder<a[]> {
    return new ArrayD(decoder);
  }
 
  public static at<a>(keys: string[], decoder: Decoder<a>): Decoder<a> {
    return keys.reduceRight((decoders, key) => Decoder.field(key, decoders), decoder);
  }
 
  public static boolean(): Decoder<boolean> {
    return new BooleanD();
  }
 
  public static fail<a>(message: string): Decoder<a> {
    return new FailD(message);
  }
 
  public static field<a>(key: string, decoder: Decoder<a>): Decoder<a> {
    return new FieldD(key, decoder);
  }
 
  public static index<a>(key: number, decoder: Decoder<a>): Decoder<a> {
    return new IndexD(key, decoder);
  }
 
  public static map<a, b>(fn: (value: a) => b, decoder: Decoder<a>): Decoder<b> {
    return new MapD(fn, decoder);
  }
 
  public static map2<a, b, c>(fn: (valueA: a, valueB: b) => c, decoderA: Decoder<a>, decoderB: Decoder<b>): Decoder<c> {
    return new Map2D(fn, decoderA, decoderB);
  }
 
  public static map3<a, b, c, d>(
    fn: (valueA: a, valueB: b, valueC: c) => d,
    decoderA: Decoder<a>,
    decoderB: Decoder<b>,
    decoderC: Decoder<c>,
  ): Decoder<d> {
    return new Map3D(fn, decoderA, decoderB, decoderC);
  }
 
  public static nonEmptyArray<a>(decoder: Decoder<a>): Decoder<NonEmptyArray<a>> {
    return Decoder.andThen(
      ([head, ...tail]) => {
        if (head) {
          return Decoder.succeed(new NonEmptyArray(head, tail));
        }
 
        return Decoder.fail('Array must have at least one value');
      },
      Decoder.array(decoder),
    );
  }
 
  public static null<a>(value: a): Decoder<a> {
    return new NullD(value);
  }
 
  public static nullable<a>(decoder: Decoder<a>): Decoder<Option<a>> {
    const decoders = new NonEmptyArray(
      Decoder.null(OptionFn.none),
      [Decoder.map<a, Option<a>>(OptionFn.some, decoder)],
    );
 
    return Decoder.oneOf(decoders);
  }
 
  public static number(): Decoder<number> {
    return new NumberD();
  }
 
  public static oneOf<a>(decoders: NonEmptyArray<Decoder<a>>): Decoder<a> {
    return new OneOfD(decoders);
  }
 
  public static string(): Decoder<string> {
    return new StringD();
  }
 
  public static succeed<a>(value: a): Decoder<a> {
    return new SucceedD(value);
  }
 
  public static unknown(): Decoder<unknown> {
    return new UnknownD();
  }
 
  public run(value: unknown): Decoded<a> {
    throw new Error('This method has to be implemented');
  }
}
 
export type Decoded<a> = Validation<NonEmptyArray<string>, a>;
 
class AndThenD<a, b> extends Decoder<b> {
  private decoderFn: (value: a) => Decoder<b>;
  private decoder: Decoder<a>;
 
  constructor(decoderFn: (value: a) => Decoder<b>, decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
    this.decoderFn = decoderFn;
  }
 
  public run(value: unknown): Decoded<b> {
    return this.decoder
      .run(value)
      .fold((errors) => ValidationFn.failure(errors), (success) => this.decoderFn(success).run(value));
  }
}
 
class ArrayD<a> extends Decoder<a[]> {
  private decoder: Decoder<a>;
 
  constructor(decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
  }
 
  public run(valueArray: unknown): Decoded<a[]> {
    if (isArray(valueArray)) {
      return valueArray.reduce((validated: Decoded<a[]>, nextValue: unknown, indexN: number): Decoded<a[]> => {
        const validatedValue = this.decoder.run(nextValue);
 
        return validatedValue.fold(
          (errorsFromValue) => {
            const errors = errorsFromValue.map((errorText) => `${errorText} at index #${indexN}`);
 
            return validated.fold(
              (errorsFromValidated) => ValidationFn.failure(errorsFromValidated.concat(errors)),
              () => ValidationFn.failure(errors),
            );
          },
          (successFromValue) => validated.map((successes) => [...successes, successFromValue]),
        );
      }, ValidationFn.success([]));
    }
 
    const message = `Value must be an array, found "${typeof valueArray}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(message));
  }
}
 
class BooleanD extends Decoder<boolean> {
  public run(value: unknown): Decoded<boolean> {
    if (typeof value === 'boolean') {
      return ValidationFn.success(value);
    }
 
    const message = `Value must be a boolean, found "${typeof value}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(message));
  }
}
 
class FailD<a> extends Decoder<a> {
  private message: string;
 
  constructor(message: string) {
    super();
    this.message = message;
  }
 
  public run(): Decoded<a> {
    return ValidationFn.failure(nonEmptyArray.of(this.message));
  }
}
 
class FieldD<a> extends Decoder<a> {
  private decoder: Decoder<a>;
  private field: string;
 
  constructor(fieldS: string, decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
    this.field = fieldS;
  }
 
  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 an object, found "${typeof valueObject}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(notObjectMsg));
  }
}
 
class IndexD<a> extends Decoder<a> {
  private decoder: Decoder<a>;
  private indexN: number;
 
  constructor(indexN: number, decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
    this.indexN = indexN;
  }
 
  public run(valueArray: unknown): Decoded<a> {
    if (isArray(valueArray)) {
      if (valueArray[this.indexN]) {
        return this.decoder
          .run(valueArray[this.indexN])
          .mapFailure((errors) => errors.map((error) => `${error} at index #${this.indexN}`));
      }
 
      const noIndexMsg = `Array missing value at index #${this.indexN}`;
      return ValidationFn.failure(nonEmptyArray.of(noIndexMsg));
    }
 
    const notArrayMsg = `Value must be an array, found "${typeof valueArray}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(notArrayMsg));
  }
}
 
class MapD<a, b> extends Decoder<b> {
  private fn: (value: a) => b;
  private decoder: Decoder<a>;
 
  constructor(fn: (value: a) => b, decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
    this.fn = fn;
  }
 
  public run(value: unknown): Decoded<b> {
    return this.decoder.run(value).map(this.fn);
  }
}
 
class Map2D<a, b, c> extends Decoder<c> {
  private fn: (valueA: a, valueB: b) => c;
  private decoderA: Decoder<a>;
  private decoderB: Decoder<b>;
 
  constructor(fn: (value: a, valueB: b) => c, decoderA: Decoder<a>, decoderB: Decoder<b>) {
    super();
    this.decoderA = decoderA;
    this.decoderB = decoderB;
    this.fn = fn;
  }
 
  public run(value: unknown): Decoded<c> {
    const decodedA = this.decoderA.run(value);
    const decodedB = this.decoderB.run(value);
    const fn = this.fn;
 
    return decodedA.fold(
      (errorsA) => decodedB.fold(
        (errorsB) => ValidationFn.failure(errorsA.concat(errorsB)),
        () => ValidationFn.failure(errorsA),
      ),
      (successA) => decodedB.fold(
        (errorsB) => ValidationFn.failure(errorsB),
        (successB) => ValidationFn.success(fn(successA, successB)),
      ),
    );
  }
}
 
class Map3D<a, b, c, d> extends Decoder<d> {
  private fn: (valueA: a, valueB: b, valueC: c) => d;
  private decoderA: Decoder<a>;
  private decoderB: Decoder<b>;
  private decoderC: Decoder<c>;
 
  constructor(
    fn: (value: a, valueB: b, valueC: c) => d,
    decoderA: Decoder<a>,
    decoderB: Decoder<b>,
    decoderC: Decoder<c>,
  ) {
    super();
    this.decoderA = decoderA;
    this.decoderB = decoderB;
    this.decoderC = decoderC;
    this.fn = fn;
  }
 
  public run(value: unknown): Decoded<d> {
    const decodedA = this.decoderA.run(value);
    const decodedB = this.decoderB.run(value);
    const decodedC = this.decoderC.run(value);
    const fn = this.fn;
 
    return decodedA.fold(
      (errorsA) => decodedB.fold(
        (errorsB) => decodedC.fold(
          (errorsC) => ValidationFn.failure(errorsA.concat(errorsB).concat(errorsC)),
          () => ValidationFn.failure(errorsA.concat(errorsB)),
        ),
        () => decodedC.fold(
          (errorsC) => ValidationFn.failure(errorsA.concat(errorsC)),
          () => ValidationFn.failure(errorsA),
        ),
      ),
      (successA) => decodedB.fold(
        (errorsB) => decodedC.fold(
          (errorsC) => ValidationFn.failure(errorsB.concat(errorsC)),
          () => ValidationFn.failure(errorsB),
        ),
        (successB) => decodedC.fold(
          (errorsC) => ValidationFn.failure(errorsC),
          (successC) => ValidationFn.success(fn(successA, successB, successC)),
        ),
      ),
    );
  }
}
 
class NullD<a> extends Decoder<a> {
  private value: a;
 
  constructor(value: a) {
    super();
    this.value = value;
  }
 
  public run(value: unknown): Decoded<a> {
    if (value === null) {
      return ValidationFn.success(this.value);
    }
 
    const message = `Value must be a null, found "${typeof value}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(message));
  }
}
 
class NumberD extends Decoder<number> {
  public run(value: unknown): Decoded<number> {
    if (typeof value === 'number') {
      return ValidationFn.success(value);
    }
 
    const message = `Value must be a number, found "${typeof value}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(message));
  }
}
 
class OneOfD<a> extends Decoder<a> {
  private decoders: NonEmptyArray<Decoder<a>>;
 
  constructor(decoders: NonEmptyArray<Decoder<a>>) {
    super();
    this.decoders = decoders;
  }
 
  public run(value: unknown): Decoded<a> {
    const firstResult = this.decoders.head.run(value);
 
    if (firstResult.isSuccess()) {
      return firstResult;
    }
 
    return this.decoders.tail.reduce((decoded: Decoded<a>, decoder: Decoder<a>) => {
      if (decoded.isSuccess()) {
        return decoded;
      }
 
      return decoder.run(value);
    }, firstResult);
  }
}
 
class StringD extends Decoder<string> {
  public run(value: unknown): Decoded<string> {
    if (typeof value === 'string') {
      return ValidationFn.success(value);
    }
 
    const message = `Value must be a string, found "${typeof value}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(message));
  }
}
 
class SucceedD<a> extends Decoder<a> {
  private value: a;
 
  constructor(value: a) {
    super();
    this.value = value;
  }
 
  public run(): Decoded<a> {
    return ValidationFn.success(this.value);
  }
}
 
class UnknownD extends Decoder<unknown> {
  public run(value: unknown): Decoded<unknown> {
    return ValidationFn.success(value);
  }
}
 
function isArray(value: unknown): value is Array<unknown> {
  return Array.isArray(value);
}
 
function isObject(value: unknown): value is { [prop: string]: unknown } {
  return typeof value === 'object';
}