Giter Site home page Giter Site logo

paulmelnikow / express-contracts Goto Github PK

View Code? Open in Web Editor NEW

This project forked from bodylabs/express-contracts

0.0 1.0 0.0 35 KB

Express.js plugin for checking request and response with rho-contracts

License: BSD 2-Clause "Simplified" License

JavaScript 100.00%

express-contracts's Introduction

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 = require('rho-contracts-fork'),
    ec = require('express-contracts');

var cc = {};

cc.request = c.object({
        body: c.object({
            foo: c.value('bar'),
        }).strict(),
    }).rename('request');

cc.responseBody = c.object({
    baz: c.value('barbar'),
}).strict().rename('responseBody');

var exampleApplicationMiddleware = function (req, res, next) {
    res.status(200).checkedJson({ baz: req.body.foo + req.body.foo });
};

var exampleErrorHandlingMiddleware = function (err, req, res, next) {
    if (err) {
        if (err instanceof ec.ValidationError) {
            res.status(400).json({ error: err.message });
        } else if (err instanceof c.ContractError) {
            res.status(500).json({ error: 'Internal Contract Violation' });
        } else {
            res.status(500).json({ error: 'Internal Server Error' });
        }
    }
};

app.use(
   require('body-parser').json(), // populates req.body
   ec.useContracts(cc.request, cc.responseBody),
   exampleApplicationMiddleware,
   exampleErrorHandlingMiddleware
);

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 (err.problemField === 'body') {
    // do something
} else if (err.problemField === 'query') {
    // do something else
} else if (err.problemField === '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.

express-contracts's People

Contributors

dlsmith avatar gmarceau avatar paulmelnikow avatar qmaurmann avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.