Flow compatible runtime type system for IO validation
npm install flow-ioA value of type Type (called "runtime type") is a representation of the type T:
``js`
class Type
name: string;
validate: (value: mixed, context: Context) => Validation
}
where Context and Validation are defined as
`js`
type ContextEntry = { key: string, name: string };
type Context = Array
type ValidationError = { value: mixed, context: Context, description: string };
type Validation
Example: a runtime type representing the type string is
`js
import * as t from 'flow-io'
export const string: Type
'string',
(v, c) => typeof v === 'string' ? t.success(v) : t.failure(v, c)
)
`
A runtime type can be used to validate an object in memory (for example an API payload)
`js
import * as t from 'flow-io'
const Person = t.object({
name: t.string,
age: t.number
})
// ok
t.fromValidation(JSON.parse('{"name":"Giulio","age":43}'), Person) // => {name: "Giulio", age: 43}
// throws Invalid value undefined supplied to : { name: string, age: number }/age: number
t.fromValidation(JSON.parse('{"name":"Giulio"}'), Person)
// doesn't throw, returns an Either
const validation = t.validate(JSON.parse('{"name":"Giulio"}'), Person)
t.map(person => console.log(person), validation)
`
Runtime types can be inspected
`js`
const Name: Type
const Age: Type
A reporter implements the following interface
`js`
export interface Reporter {
report: (validation: Validation<*>) => A;
}
This package exports two default reporters
- PathReporter: ReporterThrowReporter: Reporter
-
Example
`js
import * as t from 'flow-io'
import { PathReporter, ThrowReporter } from 'flow-io/lib/reporters/default'
const validation = t.validate('a', t.number)
console.log(PathReporter.report(validation)) // => ["Invalid value "a" supplied to : number"]
ThrowReporter.report(validation) // => throws Invalid value "a" supplied to : number
`
| Type | Flow syntax | Runtime type / combinator |
|------|-------|-------------|
| string | string | string |number
| number | | number |boolean
| boolean | | boolean |Object
| generic object | | Object |Function
| generic function | | Function |C
| instance of | C | instanceOf(C) |C
| class of | Class | classOf(C) |Array
| array | | array(A) |A & B
| intersection | | intersection([A, B]) |'s'
| literal | | literal('s') |?A
| maybe | | maybe(A) |{ [key: A]: B }
| map | | mapping(A, B) |refinement(A, predicate)
| refinement | ✘ | |{ name: string }
| object | | object({ name: string }) |[A, B]
| tuple | | tuple([A, B]) |A | B
| union | | union([A, B]) |{| name: string |}
| $Exact | | $exact({ name: string }) |(a: A) => B` | ✘ |
| function |