Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: lazy #60

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ declare global {
type Constructor<T = any> = new (...args: any[]) => T

export interface Static {
<T = any>(options: Partial<Schema<T>>): Schema<T>
new <T = any>(options: Partial<Schema<T>>): Schema<T>
<S = any, T = S>(options: Partial<Schema<S, T>>): Schema<S, T>
new <S = any, T = S>(options: Partial<Schema<S, T>>): Schema<S, T>
prototype: Schema
resolve: Resolve
from<X = any>(source?: X): From<X>
Expand All @@ -56,6 +56,7 @@ declare global {
union<const X>(list: readonly X[]): Schema<TypeS<X>, TypeT<X>>
intersect<const X>(list: readonly X[]): Schema<IntersectS<X>, IntersectT<X>>
transform<X, T>(inner: X, callback: (value: TypeS<X>) => T, preserve?: boolean): Schema<TypeS<X>, T>
lazy<S, T>(builder: () => Schema<S, T>): Schema<S, T>
}

interface Options {
Expand Down Expand Up @@ -94,6 +95,7 @@ declare global {
list?: Schema[]
dict?: Dict<Schema>
bits?: Dict<number>
builder?: () => Schema<S, T>
callback?: Function
value?: T
refs?: Dict<Schema>
Expand Down Expand Up @@ -619,6 +621,10 @@ Schema.extend('transform', (data, { inner, callback, preserve }, options) => {
}
})

Schema.extend('lazy', (data, schema, options, strict) => {
return Schema.resolve(data, schema.inner ??= schema.builder!(), options, strict)
})

type Formatter = (schema: Schema, inline?: boolean) => string
const formatters: Dict<Formatter> = {}

Expand Down Expand Up @@ -692,4 +698,6 @@ defineMethod('intersect', ['list'], ({ list }) => {

defineMethod('transform', ['inner', 'callback', 'preserve'], ({ inner }, isInner) => inner!.toString(isInner))

defineMethod('lazy', ['builder'], (schema) => (schema.inner ??= schema.builder!()).toString())

export = Schema