Effect CommunityEC
Effect Community3y ago
4 replies
bigpopakap

Handling Optional/Nullable Fields and Default Values in Schema Parsing

I'm trying to do work with optional/nullable fields when parsing a schema, and return a default if the value is
null
. For example:

A distilled version of what I'm trying to do
const ValueSchema = Schema.literal("A");
type Value = Schema.Schema.To<typeof ValueSchema>;

const ValueArraySchema: Schema.Schema<string, Value[]> = pipe(
    Schema.string,
    Schema.split(","),
    Schema.compose(Schema.array(ValueSchema)),
);


The problem is, when the array is empty, it encodes to an empty string "". Then when I decode it again, it fails because split turns "" into [""], and that fails the ValueSchema because it expects an "A".

But an empty array is a valid state, so I was thinking I'd represent that separately as
null
(sidenote: in my actual use case, it could save some storage space to set the value as
null
)

So I was thinking of doing this:
const ValueArraySchema: Schema.Schema<string | null, Value[]> = pipe(
    Schema.optionFromNullable(Schema.string),
    
    // How do I:
    // - handle Some<string> to do the same transformations as above
    // - handle None to return a default value (in this case [] as Value[])
);


I'm sure there's an easy answer, but I'm just not comfortable enough yet with schema transforms to figure it out
Was this page helpful?