flow-dynamic
v0.0.14
Published
A helper library link runtime type check to static flow check.
Downloads
6
Readme
Flow-Dynamic
Dynamic type check library which will generate corresponding static Flow Type.
For quick start
goto flow-dynamic/wiki.
Why need dynamic check?
- Data go though typed and untyped packages.(this case should be resolved by flow typed all packages)
- Data are in a complex code stream between packages,too complex for flow type between those packages. (Like graphql's resolver,which be used in graphql-relay,and the params are narrowed to a custom type).
- Data from remote,out of your control.(In this case,flow-dynamic could be used at both client and server,with single type valid logic).
Recommend Validate Style
if the params need to check is short.I prefer write them inline. like:
const wrappedFn = check1(
(v) => ({
mail:pro.isString.isEmail(v.mail) // check src.mail.
}), (v) => { // Now, the input data is validated and have a Flow type {mail:string}
// .... doing something
});
if things gets longer,should write a separated caster:
const userValid = (src) => ({
id:pro.isString(src.id),
name:pro.isString(src.name),
age:pro.isNumber(src.age),
friend:pro.isArray.isNumArr.inLength(src.friend, {max:5}),
});
In your real project,there also should be an explicitly Flow type wrote by you.
type USER = {
id:string,
name:string,
age:number,
friend:number[]
};
const userValid = (src) => ({
id:pro.isString(src.id),
name:pro.isString(src.name),
age:pro.isNumber(src.age),
friend:pro.isArray.isNumArr.inLength(src.friend, {max:5}),
});
const resolver = check1(userValid, (src:USER) => {
// .... doing something
});
Note: explicitly declare (src:USER)
to your hand-writing Flow type is helpful, will avoid wrong typo in writing userValid. If the userValid
you writing is not corresponding with USER
, flow will notice you.
Functions
- validate functions are group by the corresponding Flow type.Like
pro.isArray.isNumArr.inLength
. - There are three top namespace for
validator
.dev
pro
cvt
. pro
(product) contain allvalidator
which do not modify the input be checked.dev
(develop) is just a copy frompro
. but whenNODE_ENV != 'dev'
,all function in dev will do nothing,and just return the passed in value back. (So dev is used for those type check you think should not be checked in production environment).cvt
(convert). This namespace contain allvalidator
s which will mutate the been checked value. (Like setdefault for passin value,or clip them. or more complex usage. Like Graphql's connection cursor can be narrowed to offset when you using an array-like data model).checker
: The common checker is innormal.js
. And i hand-writed some custom checker forgraphql
(ingraphql-ck.js
have more clearly Error notice,its in namespacegraph
).- Code demonstration could be find in
__tests__
folds insrc
, and my pr tographql-relay
.