Created
August 4, 2015 15:36
-
-
Save a-s-o/e35edddf8d61c63e88d9 to your computer and use it in GitHub Desktop.
Validation system for cerebral actions using tcomb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function checkValue (msg, value, type) { | |
const check = t.validate(value, type); | |
if (!check.isValid()) { | |
console.error(msg + ' ' + check.firstError().message); | |
} | |
return value; | |
} | |
// This method accepts an object and returns a function that | |
// wraps the actual action functions | |
t.action = function t$action ({ fn, inputs, outputs, resolves, rejects }) { | |
if (__DEV__) { | |
/* eslint no-new-func: 0 */ | |
const namedFunction = (name, func) => new Function('fn', | |
`return function ${name} (){ return fn.apply(this,arguments)}` | |
)(func); | |
const Inputs = t.struct(inputs); | |
// Async actions | |
if (fn.length > 2 || resolves || rejects) { | |
const Resolved = !resolves ? t.Nil : t.struct(resolves); | |
const Rejected = !rejects ? t.Nil : t.struct(rejects); | |
return namedFunction(fn.name, (args, state, promise) => { | |
checkValue(`[${fn.name}:inputs]`, args, Inputs); | |
fn(args, state, { | |
resolve (obj) { | |
checkValue(`[${fn.name}:resolves]`, obj, Resolved); | |
promise.resolve(obj); | |
}, | |
reject (obj) { | |
checkValue(`[${fn.name}:rejects]`, obj, Rejected); | |
promise.reject(obj); | |
} | |
}); | |
}); | |
} | |
// Sync actions | |
const Returned = !outputs ? t.Nil : t.struct(outputs); | |
return namedFunction(fn.name, (args, state) => { | |
checkValue(`[${fn.name}:inputs]`, args, Inputs); | |
const result = fn(args, state); | |
checkValue(`[${fn.name}:outputs]`, result, Returned); | |
return result; | |
}); | |
} | |
return fn; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment