-
Notifications
You must be signed in to change notification settings - Fork 7
/
literal-decoders.ts
91 lines (86 loc) · 2.59 KB
/
literal-decoders.ts
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
import { optionalDecoder } from './higher-order-decoders';
import { isPojoObject, Pojo } from './pojo';
import {
decodeType,
decode,
Decoder,
DecoderFunction,
JsonLiteralForm,
} from './types';
import { tag } from './utils';
export const literal = <p extends JsonLiteralForm>(
literal: p,
): DecoderFunction<p> => (value: Pojo) => {
if (literal !== value) {
throw `The value \`${JSON.stringify(
value,
)}\` is not the literal \`${JSON.stringify(literal)}\``;
}
return literal;
};
export const tuple = <A extends Decoder<unknown>, B extends Decoder<unknown>>(
decoderA: A,
decoderB: B,
): DecoderFunction<[decodeType<A>, decodeType<B>]> => (value: Pojo) => {
if (!Array.isArray(value)) {
throw `The value \`${JSON.stringify(
value,
)}\` is not a list and can therefore not be parsed as a tuple`;
}
if (value.length !== 2) {
throw `The array \`${JSON.stringify(
value,
)}\` is not the proper length for a tuple`;
}
const [a, b] = value;
return [decode(decoderA as any)(a), decode(decoderB as any)(b)];
};
export const fieldDecoder: unique symbol = Symbol('field-decoder');
export const fields = <T extends { [key: string]: Decoder<unknown> }, U>(
decoder: T,
continuation: (x: decodeType<T>) => U,
): DecoderFunction<U> => {
const dec = (value: Pojo) => {
const decoded = decode(decoder)(value);
return continuation(decoded);
};
tag(dec, fieldDecoder);
return dec;
};
export const field = <T>(
key: string,
decoder: Decoder<T>,
): DecoderFunction<T> => {
return fields({ [key]: decoder }, (x: any) => x[key]);
};
export const record = <schema extends { [key: string]: Decoder<unknown> }>(
s: schema,
): DecoderFunction<decodeType<schema>> => (value: Pojo) => {
if (!isPojoObject(value)) {
throw `Value \`${value}\` is not of type \`object\` but rather \`${typeof value}\``;
}
return Object.entries(s)
.map(([key, decoder]: [string, any]) => {
if (decoder[fieldDecoder] === true) {
return [key, decode(decoder)(value)];
}
if (!value.hasOwnProperty(key)) {
if ((decoder as any)[optionalDecoder]) {
return [key, undefined];
}
throw `Cannot find key \`${key}\` in \`${JSON.stringify(value)}\``;
}
try {
const jsonvalue = value[key];
return [key, decode(decoder)(jsonvalue)];
} catch (message) {
throw (
message +
`\nwhen trying to decode the key \`${key}\` in \`${JSON.stringify(
value,
)}\``
);
}
})
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
};