-
Notifications
You must be signed in to change notification settings - Fork 5
/
json.ts
53 lines (46 loc) · 1.09 KB
/
json.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
import { use } from './custom'
import {
createFail,
InternalRuntype,
isFail,
propagateFail,
Runtype,
setupInternalRuntype,
} from './runtype'
export const jsonRuntype = setupInternalRuntype<unknown>(
(v, failOrThrow) => {
if (!(typeof v === 'string')) {
return createFail(failOrThrow, 'expected a json string', v)
}
try {
const jsonData = JSON.parse(v)
return jsonData
} catch (err) {
return createFail(
failOrThrow,
'expected a json string: ' + String(err),
v,
)
}
},
{ isPure: false },
)
/**
* A String that is valid json
*/
export function json<T>(rt: Runtype<T>): Runtype<T> {
return setupInternalRuntype<any>(
(v, failOrThrow) => {
const n = (jsonRuntype as InternalRuntype<any>)(v, failOrThrow)
if (isFail(n)) {
return propagateFail(failOrThrow, n, v)
}
const validationResult = use(rt, n)
if (!validationResult.ok) {
return propagateFail(failOrThrow, validationResult.error, v)
}
return validationResult.result
},
{ isPure: true },
)
}