1 | import type {SchemaObjCxt} from ".."
|
2 | import {_, getProperty, stringify} from "../codegen"
|
3 | import {checkStrictMode} from "../util"
|
4 |
|
5 | export function assignDefaults(it: SchemaObjCxt, ty?: string): void {
|
6 | const {properties, items} = it.schema
|
7 | if (ty === "object" && properties) {
|
8 | for (const key in properties) {
|
9 | assignDefault(it, key, properties[key].default)
|
10 | }
|
11 | } else if (ty === "array" && Array.isArray(items)) {
|
12 | items.forEach((sch, i: number) => assignDefault(it, i, sch.default))
|
13 | }
|
14 | }
|
15 |
|
16 | function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {
|
17 | const {gen, compositeRule, data, opts} = it
|
18 | if (defaultValue === undefined) return
|
19 | const childData = _`${data}${getProperty(prop)}`
|
20 | if (compositeRule) {
|
21 | checkStrictMode(it, `default is ignored for: ${childData}`)
|
22 | return
|
23 | }
|
24 |
|
25 | let condition = _`${childData} === undefined`
|
26 | if (opts.useDefaults === "empty") {
|
27 | condition = _`${condition} || ${childData} === null || ${childData} === ""`
|
28 | }
|
29 |
|
30 |
|
31 | gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)
|
32 | }
|