-
Notifications
You must be signed in to change notification settings - Fork 89
Is converting values in the scope of this library ? #56
Copy link
Copy link
Closed
Labels
Milestone
Description
A common use case when validating data from external APIs is to have dates encoded as strings.
Let's say I get the following data from a JSON API:
{ "date": "2015-10-12 12:00:00" }I would want to represent it with the following Runtype:
Record({ date: InstanceOf(Date) })Is there a simple way to go from the first to the second without having to use an intermediate Record({ date: String }) runtype, and doing the validation ?
I think that having a convertFrom method on the Runtype interface would help a lot.
interface Runtype<A> {
// ...
convertFrom<B> : (checkBefore: (x: any) => B) => Runtype<A>;
}The returned Runtype would be exactly the same, but the check method would be changed to include the additional validation in checkBefore before the one from the initial Runtype.
I could then do:
const Input = Record({
date: InstanceOf(Date).convertFrom(x => {
const strX = String.check(x);
const timestamp = Date.parse(strX);
if(isNan(timestamp)) {
throw new ValidationError('Invalid date string ' + strX);
}
return new Date(timestamp);
})
});Do you think it could be added to the library (I would be willing to do it)?
Reactions are currently unavailable