Skip to content

Commit

Permalink
Add a conversion registry
Browse files Browse the repository at this point in the history
  • Loading branch information
lecafard committed Jan 30, 2025
1 parent 4d8261f commit 5217fcc
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 3 deletions.
40 changes: 40 additions & 0 deletions src/type/registry/convert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/type
The MIT License (MIT)
Copyright (c) 2017-2025 Haydn Paterson (sinclair) <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
import { TSchema } from "../schema";
import { BaseRegistry } from "./base";

export type ConvertRegistryFunction<TSchema> = (schema: TSchema, value: unknown, data?: any) => unknown

const ConvertRegistry = new BaseRegistry<ConvertRegistryFunction<TSchema>>()

export const Entries = ConvertRegistry.Entries
export const Clear = ConvertRegistry.Clear
export const Delete = ConvertRegistry.Delete
export const Has = ConvertRegistry.Has
export const Set = ConvertRegistry.Set
export const Get = ConvertRegistry.Get
1 change: 1 addition & 0 deletions src/type/registry/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ THE SOFTWARE.
---------------------------------------------------------------------------*/

export * as ConvertRegistry from './convert'
export * as FormatRegistry from './format'
export * as TypeRegistry from './type'
14 changes: 11 additions & 3 deletions src/value/convert/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { Check } from '../check/index'
import { Deref, Pushref } from '../deref/index'
import { Kind } from '../../type/symbols/index'

import { ConvertRegistry } from '../../type/registry/index'
import type { TSchema } from '../../type/schema/index'
import type { TArray } from '../../type/array/index'
import type { TBigInt } from '../../type/bigint/index'
Expand Down Expand Up @@ -250,7 +251,12 @@ function FromUnion(schema: TUnion, references: TSchema[], value: any): unknown {
}
return value
}
function Visit(schema: TSchema, references: TSchema[], value: any): unknown {
function FromKind(schema: TSchema, references: TSchema[], value: unknown, data?: Map<string, any>): unknown {
if (!ConvertRegistry.Has(schema[Kind])) return Default(value)
const func = ConvertRegistry.Get(schema[Kind])!
return func(schema, value, data && data.get(schema[Kind]))
}
function Visit(schema: TSchema, references: TSchema[], value: any, data?: Map<string, any>): unknown {
const references_ = Pushref(schema, references)
const schema_ = schema as any
switch (schema[Kind]) {
Expand Down Expand Up @@ -293,18 +299,20 @@ function Visit(schema: TSchema, references: TSchema[], value: any): unknown {
case 'Union':
return FromUnion(schema_, references_, value)
default:
return Default(value)
return FromKind(schema, references_, value, data)
}
}
// ------------------------------------------------------------------
// Convert
// ------------------------------------------------------------------
/** `[Mutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible. */
export function Convert(schema: TSchema, references: TSchema[], value: unknown, data?: Map<string, any>): unknown
/** `[Mutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible. */
export function Convert(schema: TSchema, references: TSchema[], value: unknown): unknown
/** `[Mutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible. */
export function Convert(schema: TSchema, value: unknown): unknown
/** `[Mutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible. */
// prettier-ignore
export function Convert(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1])
return args.length >= 3 ? Visit(args[0], args[1], args[2], args[3]) : Visit(args[0], [], args[1])
}
32 changes: 32 additions & 0 deletions test/runtime/value/convert/custom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Value } from '@sinclair/typebox/value'
import { Kind, TSchema, ConvertRegistry } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/convert/Custom', () => {
// ---------------------------------------------------------
// Fixtures
// ---------------------------------------------------------
afterEach(() => ConvertRegistry.Clear())
// ---------------------------------------------------------
// Test
// ---------------------------------------------------------
it('Should convert value with a function', () => {
const T = { [Kind]: 'Custom' } as TSchema
ConvertRegistry.Set('Custom', (_, t) => !!t)
const R = Value.Convert(T, true)
Assert.IsEqual(R, false)
})
it('Should convert value using params', () => {
const T = { [Kind]: 'Custom', params: ['a'] } as TSchema
ConvertRegistry.Set('Custom', (s, t) => `${s.params[0]}_${t}`)
const R = Value.Convert(T, "test")
Assert.IsEqual(R, "a_test")
})

it('Should convert value using injected data', () => {
const T = { [Kind]: 'Custom' } as TSchema
ConvertRegistry.Set('Custom', (_s, t, v) => `${v}_${t}`)
const R = Value.Convert(T, [], "test", new Map([['Custom', 'b']]))
Assert.IsEqual(R, "b_test")
})
})

0 comments on commit 5217fcc

Please sign in to comment.