diff --git a/src/SchemaItem.ts b/src/SchemaItem.ts index bdfb303..18079f1 100644 --- a/src/SchemaItem.ts +++ b/src/SchemaItem.ts @@ -1,7 +1,9 @@ /* eslint-disable id-length */ import { objectClean } from '@dzeio/object-util' import { StandardSchemaV1 } from '@standard-schema/spec' -import Schema, { SchemaNullable } from './Schema' +import SchemaNullable from 'items/nullable' +import { isNull } from './helpers' +import Schema, { parceable } from './Schema' import { SchemaJSON, ValidationError, ValidationResult } from './types' export default abstract class SchemaItem implements StandardSchemaV1 { @@ -71,6 +73,18 @@ export default abstract class SchemaItem implements StandardSchemaV1 } } + @parceable() + public defaultValue(value: Type, strict = true) { + this.addPreProcess((input) => { + if (strict && isNull(input) || !strict && !input) { + return value + } + return input + }) + + return this + } + public attrs(...attributes: Array) { this.attributes.concat(attributes) return this diff --git a/src/helpers.ts b/src/helpers.ts index 657bac1..65ad671 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -5,6 +5,10 @@ import SchemaNullable from 'items/nullable' import SchemaObject from 'items/object' import type SchemaItem from 'SchemaItem' +export function isNull(value: unknown): value is undefined | null { + return typeof value === 'undefined' || value === null +} + export function parseQuery(model: T, query: URLSearchParams, opts?: Parameters[1]): ReturnType { const record: Record = {} for (const [key, value] of query) {