-
Notifications
You must be signed in to change notification settings - Fork 40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Combinator to help creating migrations between types #82
Comments
We've used it in our codebase. export const migrate = <A, B, I, O>(
from: t.Decoder<I, A>,
to: t.Type<B, O, I>,
migrate: (a: A) => B,
name?: string
): t.Type<B, O, I> =>
new t.Type(
name === undefined ? `migrate(${from.name}, ${to.name})` : name,
to.is,
(i, context) => to.validate(i, context).orElse(_ => from.validate(i, context).map(migrate)),
to.encode
) @gcanti I'm pushing for its inclusion; ok with it? |
Hey @sledorze! I worked on a library that does kinda the same. maybe I could use the decoder internally instead of doing that myself. I wonder what do you think: https://github.com/Schniz/migratype import {migratype, TypeOf, LevelsOf} from 'migratype';
import * as t from 'io-ts';
const UserType = migratype("User", t.string)
.extend({
type: t.type({ name: t.string }),
migration: name => right({ name })
})
type User = TypeOf<typeof UserType>; // { name: string }
type AllCombinationsOfUser = LevelsOf<typeof UserType>; // string | { name: string } |
@Schniz Also this is the export const migratePartial = <A, B, I, O>(
from: t.Decoder<I, A>,
to: t.Type<B, O, I>,
migration: (a: A, context: t.Context) => Either<t.Errors, B>,
name?: string
): t.Type<B, O, I> =>
new t.Type(
name === undefined ? `migratePartial(${from.name}, ${to.name})` : name,
to.is,
(i, context) =>
to
.validate(i, context)
.orElse(_ => from.validate(i, context).chain(v => migration(v, context))),
to.encode
) @gcanti pinging again, would you accept a PR? |
Provides a mean to decode a (previous) type and encode a new one.
Two flavors; one for which the conversion is always possible (total); the other for which the conversion is partial.
The resulting Type is minimal but breaks some laws (namely it cannot decode what it has encoded.
Sketch:
Another version (not copied here) handles also decoding the new Type.
I'm opening the discussion to debate what's the most useful for other users.
The text was updated successfully, but these errors were encountered: