api-check
If that build is ever red or the coverage is ever less than 100% then I want you to flame me on twitter (@kentcdodds) and be sure to mention how disappointed @josepheames would be in me
It's like ReactJS propTypes
without React. Actually,
it's very heavily inspired by this concept. It's purpose is for normal JavaScript functions rather than just React
Components.
Installation
$ npm i -S api-check
or $bower i -S api-check
api-check utilizes UMD, so you can:
var apiCheck = require('api-check')(/* your custom options, checkers*/);
Also available as an AMD module or as apiCheck
on global
Example
Note, there are a bunch of tests. Those should be instructive as well.
var myApiCheck = /* config options */ output: prefix: 'app/lib Name' suffix: 'Good luck!' docsBaseUrl: 'http://www.example.com/error-docs#' verbose: false /* custom checkers if you wanna */; // given we have a function like this: { // we can define our api as the first argument to myApiCheck.warn myApiCheck; // do stuff}// the function above can be called like so:; // if it were called like so, a descriptive warning would be logged to the console; // here's something a little more complex (this is what's in the screenshot and [the demo](http://jsbin.com/hibocu/edit?js,console,output))var myCheck = output: prefix: 'myApp' suffix: 'see docs -->' docsBaseUrl: 'http://example.com/error-descriptions#' ; { myCheck; // do stuff} var person = name: first: 'Matt' last: 'Meese' age: 27 isOld: false ipAddress: '127.0.0.1' {}; {}var options = 'whatever I want because it is an "any" type'; console;; console;; // <-- options is optional console;; // <-- this would fail because person is not optional personipAddress = 'Invalid IP Address!!!'; console;; // <-- this would fail because the ipAddress checker would fail // if you only wish to check the first argument to a function, you don't need to supply an array. var libCheck = ; // you don't HAVE to pass anything if you don't want to. { var errorMessage = ; if !errorMessage // success else if typeof errorMessage === 'string' // there was a problem and errorMessage would like to tell you about it }; // <-- success!
Differences from React's propTypes
Differences in Supported Types noted below with a *
- All types are required by default, to set something as optional, append
.optional
- checkApi.js does not support
element
andnode
types - checkApi.js supports a few additional types
object
fails on null. Useobject.nullOk
if you don't want that
Similarities to React's propTypes
This project was totally written from scratch, but it (should) support the same api as React's propTypes
(with the
noted difference above). If you notice something that functions differently, please file an issue.
apiCheck(), apiCheck.warn(), and apiCheck.throw()
These functions do the same thing, with minor differences. In both the warn
and throw
case, a message is generated
based on the arguments that the function was received and the api that was defined to describe what was wrong with the
invocation.
In all cases, an object is returned with the following properties:
argTypes (arrayOf[Object])
This is an array of objects representing the types of the arguments passed.
apiTypes (arrayOf[Object])
This is an object representing the types of the api. It's a whole language of its own that you'll hopefully get after looking at it for a while.
failed (boolean)
Will be false when the check passes, and true when it fails
passed (boolean)
Will be true when the check passes, and false when it fails
message (string)
If the check failed, this will be a useful message for display to the user. If it passed, this will be an empty string
Also note that if you only have one argument, then the first argument to the apiCheck
function can simply be the
checker function. For example:
;
The second argument can either be an arguments-like object or an array.
Supported types
array
apiCheck; // <-- passapiCheck; // <-- fail
bool
apiCheck; // <-- passapiCheck; // <-- fail
func
apiCheck; // <-- passapiCheck; // <-- fail
func.withProperties *
Not available in React's propTypes
var checker = apiCheckfunc;{}winningtype = 'awesomeness';; // <--pass {}; // <-- fail
number
apiCheck; // <-- passapiCheck; // <-- fail
object *
null
fails, use object.nullOk
to allow null to pass
apiCheckobject{}; // <-- passapiCheckobject; // <-- failapiCheckobjectnull; // <-- fail
object.nullOk *
Not available in React's propTypes
apiCheckobject; // <-- passapiCheckobject; // <--- falseapiCheckobject; // <-- pass
string
apiCheck; // <-- passapiCheck; // <-- fail
range
apiCheck4; // <-- passapiCheck500; // <-- fail
greaterThan
apiCheck200; // <-- passapiCheck-20; // <-- failapiCheck'Frogs!'; // <-- fail
lessThan
apiCheck50; // <-- passapiCheck0; // <-- failapiCheck'Frogs!'; // <-- fail
instanceOf
apiCheck; // <-- passapiCheck'wanna go on a date?'; // <-- fail
oneOf
apiCheck'Treek'; // <-- passapiCheck'Snoova'; // <-- fail
oneOfType
apiCheck{}; // <-- passapiCheck'Kess'; // <-- fail
arrayOf
apiCheck'Huraga' 'Japar' 'Kahless'; // <-- passapiCheck123 456 789 123 456 789; // <-- pass (for realz)apiCheck'a' 'b' 'c'; // <-- fail
typeOrArrayOf *
Not available in React's propTypes
Convenience checker that combines oneOfType
with arrayOf
and whatever you specify. So you could take this:
apiCheck;
with
apiCheck;
which is a common enough use case to justify the checker.
apiCheck'string'; // <-- passapiCheck'array' 'of strings'; // <-- passapiCheck'array' false; // <-- failapiCheck32; // <-- fail
objectOf
apiChecka: true false b: false true; // <-- passapiChecka: 'not a number?' b: 'yeah, me neither (◞‸◟;)'; // <-- fail
shape *
Note: React propTypes
does support shape
, however it does not support the strict
option
If you add .strict
to the shape
, then it will enforce that the given object does not have any extra properties
outside those specified in the shape
. See below for an example...
apiCheckshape name: checkersshape first: checkersstring last: checkersstring age: checkersnumber isOld: checkersbool walk: checkersfunc childrenNames: checkers name: first: 'Matt' last: 'Meese' age: 27 isOld: false {} childrenNames: ; // <-- passapiCheckshape mint: checkersbool chocolate: checkersboolmint: true; // <-- fail
Example of strict
var strictShape = apiCheckshape cookies: apiCheckbool milk: apiCheckbool popcorn: apiCheckbooloptionalstrict; // <-- that! ; // <-- fail because the extra `candy` property ; // <-- pass because it has no extra properties and `popcorn` is optional
Note, you can also append .optional
to the .strict
(as in: apiCheck.shape({}).strict.optional
)
shape.onlyIf *
Not available in React's propTypes
This can only be used in combination with shape
apiCheckshape cookies: apiCheckshapecookies: true mint: true chips: true; // <-- pass apiCheckshape cookies: apiCheckshapechips: true; // <-- pass (cookies not specified) apiCheckshape cookies: apiCheckshapecookies: true; // <-- fail
shape.ifNot *
Not available in React's propTypes
This can only be used in combination with shape
apiCheckshape cookies: apiCheckshapecookies: true; // <-- pass apiCheckshape cookies: apiCheckshapecookies: true chips: true; // <-- fail
requiredIfNot *
Not available in React's propTypes
This can only be used in combination with shape
checker = checkersshape foobar: checkersshape foobaz: checkersobjectoptional baz: checkersstringoptional foo: checkersstringoptional;; // <-- passes ; // <-- fails
all
Not available in React's propTypes
This can only be used in combination with shape.requiredIfNot
checker = checkersshape foobar: checkersshaperequiredIfNotall'foobaz' 'baz' checkersbool foobaz: checkersobjectoptional baz: checkersstringoptional foo: checkersstringoptional;; // <-- fails ; // <-- passes ; // <-- passes
args *
Not available in React's propTypes
This will check if the given item is an arguments
-like object (non-array object that has a length property)
{ apiCheck; // <-- pass}apiCheck; // <-- failapiCheck; // <-- failapiCheck; // <-- passapiCheck; // <-- fail
any
apiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- failapiCheckany; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- passapiCheck; // <-- Syntax error.... ಠ_ಠ
Custom Types
You can specify your own type. You do so like so:
var myCheck = output: prefix: 'myCheck'; { if !/{3}\d{1,3}/ return apiCheckutils; };ipAddressCheckertype = 'ipAddressString'; { myCheck;}
Then, if you invoked that function like this:
;
It would result in a warning like this:
myCheck apiCheck failed! `Argument 1` passed, `value` at `Argument 2` must be `ipAddressString`
You passed:
[
"hello",
"not-an-ip-address"
]
With the types:
[
"string",
"string"
]
The API calls for:
[
"String",
"ipAddressString"
]
There's actually quite a bit of cool stuff you can do with custom types checkers. If you want to know what they are, look at the tests or file an issue for me to go document them. :-)
apiCheck.utils
When writing custom types, you may find the utils
helpful. Please file an issue to ask me to improve documentation for
what's available. For now, check out api-check-utils.test.js
Customization
Note, obviously, these things are specific to apiCheck
and not part of React propTypes
When you create your instance of apiCheck
, you can configure it with different options as part of the first argument.
config.output
You can specify some extra options for the output of the message.
var myApiCheck = output: prefix: 'Global prefix' suffix: 'global suffix' docsBaseUrl: 'https://example.com/errors-and-warnings#' verbose: false // <-- defaults to false disabled: false // <-- defaults to false, set this to true in production;
You can also specify an output
object to each apiCheck()
, apiCheck.throw()
, and apiCheck.warn()
request:
;
A failure with the above configuration would yield something like this:
Global prefix instance prefix {{error message}} instance suffix global suffix https://example.com/errors-and-warnings#example-error-additional-info
As an alternative to urlSuffix
, you can also specify a url
:
;
getErrorMessage
This is the method that apiCheck uses to get the message it throws or console.warns. If you don't like it, feel free to
make a better one by simply: apiCheck.getErrorMessage = function(api, args, output) {/* return message */}
handleErrorMessage
This is the method that apiCheck uses to throw or warn the message. If you prefer to do your own thing, that's cool.
Simply apiCheck.handleErrorMessage = function(message, shouldThrow) { /* throw or warn */ }
Disable apiCheck
It's a good idea to disable the apiCheck in production. You can disable your own instance of apiCheck
as part of
the options
, but it's probably just better to disable apiCheck
globally. I recommend you do this before you (or
any of you dependencies) create an instance of apiCheck
. Here's how you would do that:
var apiCheck = ;apiCheckglobalConfigdisabled = true;
Credits
This library was written by Kent C. Dodds. Again, big credits go to the team working on React for thinking up the api. This library was written from scratch, but I'd be lying if I didn't say that I referenced their functions a time or two.