A
arktype3mo ago
Dimava

Morph on failure

I have a type
const T = type({ id: "string>0", label: "string>0" })
const T = type({ id: "string>0", label: "string>0" })
and objects of type { id: string>0, label?: string>=0 } and want to create a type that will try to morph with (o: { id: string>0, label?: string>=0 }) => { o.label ||= o.id } only on failure, and then try to revalidate with the same validator What's the best way to do that?
2 Replies
Dimava
DimavaOP3mo ago
I guess I need an ordered union for this My current solution
export function migrate<const def>(
def: type.validate<def>,
...migrations: type.Any[]
) {
const T = type(def) as type.Any
return type('unknown.any')
.pipe((v, _ctx) => {
let result = T(v)
if (!(result instanceof type.errors))
return result
for (const migration of migrations) {
const migResult = migration(result)
if (!(migResult instanceof type.errors)) {
result = migResult
}
}
return T(result)
})
}
export function migrate<const def>(
def: type.validate<def>,
...migrations: type.Any[]
) {
const T = type(def) as type.Any
return type('unknown.any')
.pipe((v, _ctx) => {
let result = T(v)
if (!(result instanceof type.errors))
return result
for (const migration of migrations) {
const migResult = migration(result)
if (!(migResult instanceof type.errors)) {
result = migResult
}
}
return T(result)
})
}
ssalbdivad
ssalbdivad3mo ago
Ordered unions are a thing but not something I've exposed yet in the primary API I'm going to use them for match expressions though since that's essentially what pattern matching is
Want results from more Discord servers?
Add your server