effect icon indicating copy to clipboard operation
effect copied to clipboard

JSON Schema to Schema converter

Open huypham50 opened this issue 1 year ago • 4 comments

What is the problem this feature would solve?

Discussed on discord

import * as S from "@effect/schema/Schema";
import * as JSONSchema from "@effect/schema/JSONSchema";

// I want to construct a schema
const schema = S.struct({...})
const jsonSchema = JSONSchema.to(UserSchema);

// I want to store the serialized version of the schema (json schema) in a remote database
await orm.insertRow({..., jsonSchema})

// I want to retrieve the row, deserialize, and keep working with it
const storedJsonSchema = await orm.getRow(...) // same as jsonSchema
const originalSchema = JSONSchema.deserialize(storedJsonSchema) // same as schema - looking for this

What is the feature you are proposing to solve the problem?

Would love a deserialize method to convert a json schema back to an effect schema. Thanks for the great work!

What alternatives have you considered?

Plain json schema + ajv

huypham50 avatar Nov 22 '23 05:11 huypham50

@huypham50 originalSchema will be a Schema<unknown>, AFAIK there's no way to get back the type of the orginal schema

gcanti avatar Nov 22 '23 13:11 gcanti

@gcanti I think that should be fine, are there native type guards or we'll have to do something like this?

if ('type' in originalSchema && originalSchema.type === 'object')

huypham50 avatar Nov 22 '23 19:11 huypham50

I mean, even if you managed to define deserialize, what use do you make of the returned schema if it is typed as Schema<unknown>?

gcanti avatar Nov 22 '23 19:11 gcanti

I'd imagine something like this, let me know if it's not feasible!

traverse through the fields in Schema<unknown>
switch (typeof field)
    case string -> extract string annotations (minLength, pattern, format, etc)
    case number -> extract number annotations (min, max, integer, etc)
    ...
add/remove annotations from existing fields
convert back to json schema
update schema in the database

huypham50 avatar Nov 22 '23 20:11 huypham50