defaults.ts 1.2 KB

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