createCustomSchematizer
The createCustomSchematizer function creates a custom Schematizer that can convert schemas from any validation library into TinyBase schemas.
createCustomSchematizer(
unwrapSchema: (schema: any, defaultValue?: any, allowNull?: boolean, required?: boolean) => [any, any, boolean] | [any, any, boolean, undefined | boolean],
getProperties: (schema: any) => any,
getPropertyRequired?: (schema: any, propertyId: string, propertySchema: any) => undefined | boolean,
): Schematizer| Type | Description | |
|---|---|---|
unwrapSchema | (schema: any, defaultValue?: any, allowNull?: boolean, required?: boolean) => [any, any, boolean] | [any, any, boolean, undefined | boolean] | A function that unwraps a schema to extract the base type, default value, nullable flag, and optional required flag. It should recursively unwrap optional/nullable wrappers and return a tuple of [schema, defaultValue, allowNull, required]. |
getProperties | (schema: any) => any | A function that extracts the properties/entries/shape from an object schema. Returns undefined if the schema is not an object. |
getPropertyRequired? | (schema: any, propertyId: string, propertySchema: any) => undefined | boolean | An optional function that extracts whether an object property is required. |
| returns | Schematizer | A new |
This function allows you to build schematizers for validation libraries not natively supported by TinyBase. You provide two functions: one to unwrap optional/nullable/default wrappers from your library's schemas, and one to extract object properties.
Example
This example creates a custom schematizer for a hypothetical validation library.
import {createCustomSchematizer} from 'tinybase/schematizers';
// Hypothetical library has schemas like:
// {type: 'string'}, {type: 'optional', inner: ...}, etc.
const unwrapSchema = (
schema,
defaultValue,
allowNull,
required = true,
) => {
if (schema.type === 'optional') {
return unwrapSchema(schema.inner, defaultValue, allowNull, false);
}
if (schema.type === 'nullable') {
return unwrapSchema(schema.inner, defaultValue, true, required);
}
return [
schema,
defaultValue ?? schema.default,
allowNull ?? false,
required,
];
};
const getProperties = (schema) => schema.fields;
const schematizer = createCustomSchematizer(unwrapSchema, getProperties);
const tablesSchema = schematizer.toTablesSchema({
pets: {type: 'object', fields: {name: {type: 'string'}}},
});
console.log(tablesSchema);
// -> {pets: {name: {type: 'string', required: true}}}
Since
v7.1.0