feat: Add defaultValue to schemas

This commit is contained in:
Florian Bouillon 2025-03-25 14:31:56 +01:00
parent 7d083dde25
commit 8fa83d2b1f
Signed by: Florian Bouillon
GPG Key ID: 7676FF78F3BC40EC
2 changed files with 19 additions and 1 deletions

View File

@ -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<Type = any> implements StandardSchemaV1<Type> {
@ -71,6 +73,18 @@ export default abstract class SchemaItem<Type = any> 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<string>) {
this.attributes.concat(attributes)
return this

View File

@ -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<T extends SchemaItem>(model: T, query: URLSearchParams, opts?: Parameters<T['parse']>[1]): ReturnType<T['parse']> {
const record: Record<string, unknown> = {}
for (const [key, value] of query) {