express-contracts
Express.js plugin for checking request and response with rho-contracts
Usage
You must use the Body Labs package, rho-contracts-fork
:
"dependencies": "rho-contracts-fork": "^1.3.0"
var c = ec = ; var cc = {}; ccrequest = cobject body: cobject foo: cvalue'bar' ; ccresponseBody = cobject baz: cvalue'barbar'; var { resstatus200;}; var { if err if err instanceof ecValidationError resstatus400; else if err instanceof cContractError resstatus500; else resstatus500; }; app;
Note the middleware useContracts(requestContract, responseBodyContract)
distinguishes between ValidationError
(for failures of requestContract
) and
ContractError
(for failures of responseBodyContract
), which callers will
likely wish to handle differently.
Furthermore, note that the middleware works by extending res
with a method
checkedJson
which checks responseBodyContract
before calling res.json
,
thus it is easy to "jump out" of the contract e.g. to send an error.
Finally, there is an asymmetry between the requestContract
, which is run over
the whole request (but only body
, query
, and params
are actually
checked), and the responseBodyContract
, which is only run over the payload
that eventually becomes the res.body
.
As of 2.2.0, the exported ValidationError
says which of the three checked
fields caused the (first seen) error, under the key problemField
, e.g.
if errproblemField === 'body' // do something else if errproblemField === 'query' // do something else else if errproblemField === 'params' // do yet something else else // should not happen unless we start checking more fields
Installation
npm install rho-contracts-fork express-contracts
Contribute
- Issue Tracker: github.com/bodylabs/express-contracts/issues
- Source Code: github.com/bodylabs/express-contracts
Pull requests welcome!
Support
If you are having issues, please let us know.
License
The project is licensed under the two-clause BSD license.