-
Notifications
You must be signed in to change notification settings - Fork 10
/
serverHelpers.go.tmpl
54 lines (45 loc) · 1.5 KB
/
serverHelpers.go.tmpl
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
{{ define "serverHelpers" }}
{{- $types := .Types -}}
{{- $typeMap := .TypeMap }}
const JS_TYPES = [
"bigint",
"boolean",
"function",
"number",
"object",
"string",
"symbol",
"undefined"
]
{{ range $_, $type := $types }}
const validate{{ $type.Name }} = (value: any) => {
{{ range $_, $field := $type.Fields }}
{{ if $field.Optional }}
if ("{{template "fieldName" dict "Field" $field }}" in value && !validateType(value["{{template "fieldName" dict "Field" $field }}"], "{{template "jsType" dict "Type" (coalesce $field.Type $type.Type) "TypeMap" $typeMap}}")) {
return false
}
{{ else }}
if (!("{{template "fieldName" dict "Field" $field }}" in value) || !validateType(value["{{template "fieldName" dict "Field" $field }}"], "{{template "jsType" dict "Type" (coalesce $field.Type $type.Type) "TypeMap" $typeMap}}")) {
return false
}
{{ end }}
{{ end }}
return true
}
{{ end }}
const TYPE_VALIDATORS: { [type: string]: (value: any) => boolean } = {
{{ range $_, $type := $types }}
{{ $type.Name }}: validate{{ $type.Name }},
{{ end }}
}
const validateType = (value: any, type: string) => {
if (JS_TYPES.indexOf(type) > -1) {
return typeof value === type;
}
const validator = TYPE_VALIDATORS[type];
if (!validator) {
return false;
}
return validator(value);
}
{{ end }}