Using api-check methods within custom checker
Hey @kentcdodds,
I was hoping I could use api-check methods within a custom checker. Perhaps something sort of like this:
randomData: function (val, name, location) {
ac.throw([
ac.shape({
"name": ac.string,
"site": ac.string,
"forwardRegex": ac.string,
"reverseRegex": ac.string,
"cutType": ac.number,
"dsForward": ac.number,
"dsReverse": ac.number,
"usForward": ac.number,
"usReverse": ac.number
})
], val);
},
But I wasn't sure how to go about doing so exactly.. Is there a good way of doing this?
Thanks for all your time! It is much appreciated! Thomas
I hope my question above was clear. I am basically trying to make a custom checker that leverages already existing types.
I'm thinking that maybe the best way to do this is to export the custom checker as a function attached to the api-check instance. For example:
var ac = require('api-check')({
/* config options */
output: {
prefix: '',
suffix: 'Good luck!',
docsBaseUrl: 'no docs yet!'
},
verbose: false
}, {
});
ac.customChecker1 = ac.shape({
features: ac.array,
specialNumber: ac.number,
})
module.exports = ac;
It seems to me that this should work (so long as I don't override anything in the api-check name space by accident). Any thoughts?
Thanks! Thomas
This should work fine. Another thing to try is that second parameter to the factory is an object of custom checkers which are added to your instance for you.
I should also note that your first example actually calls ac.throw. You shouldn't actually throw errors in a checker, you simply return them.
Something like this should work:
return ac(ac.string, 32).message;
Actually, sorry, you need to return an error object, so something more like this:
return new Error(ac(ac.string, 32).message);
However, that will contain a bit more api-check specific error info, so even better would be:
return ac.string(32);
So, as a full checker:
function myChecker(val, name, location, entireObjectIfInAShape) {
// entireObjectIfInAShape only applies when the checker is being run in a `shape` like in the case of `shape.onlyIf` and `shape.requiredIf` etc.
return ac.string(val, name, location, entireObjectIfInAShape); // or whatever else you want to do...
}