npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-responder

v0.2.0

Published

Express.js middleware abstracting error vs success responses.

Downloads

10

Readme

Express.js Responder

Express.js middleware abstracting error vs success responses.

NPM Version NPM Downloads Build Coverage Status

INSTALLING

$ npm install express-responder --save

FEATURES

  • Middleware control flow
  • Uniformed error handling
  • Request validation
  • Response validation
  • Content-Type repsonse negotiation

USAGE

The rationale behind this module is to reduce the amount of repetitive code required to validate a request cycle in express.js/ connect. Ever find yourself writing code like this?

function(req,res,next){
  UserModel.findOne({
    _id:"[email protected]"
  }, function(err, user){

    if( err){
      res.send(500, err);
    }else{
      res.send(user);
    }
  });
}

We were tired of seeing this throughout our express.js apps so this module was born, converting the above into this:

function(req,res,next){
  UserModel.findOne({
    _id:"[email protected]"
  }, function(err, user){
    res.continueOrError(err, user, next);
  });
}

Basic usage

var responder = require('express-responder')();
var express = require('express');
var app = express();

app.use(responder.continue());
// ... Other middleware like session and static

app.get('/api/v1/users', function(req,res,next){
  UserModel.find()
  .exec(function(err, user){
    res.continueOrError(err, user, next);
  });
});

// ... After all your routes
app.use(responder.respond());

API

Middleware
  • responder.continue()

    Register the middleware exposing the methods below on request and response objects.

  • responder.respond([options])

    Register middleware to handle 404 and Error responses, along with content negotiation.

    Options

    • jsonpCallbackName

      Change the querystring parameter used to detect a JSONP request.

      Default: 'callback'

      app.set('jsonp callback name', '__jsonpCallback__');
      
      app.use(responder.respond({
        jsonpCallbackName: app.get('jsonp callback name')
      });
    • respondWith

      Pass custom callbacks for each content-type. Supports html, json, xml, jsonp, text and default types.

      app.use(responder.respond({
        respondWith: {
          text: function(res, response){
            res.send('text');
          },
          json: function(res, response){
            res.type('text').send('json');
          },
          jsonp: function(res, response){
            res.type('text').send('jsonp');
          },
          xml: function(res, response){
            res.send('xml');
          },
          html: function(res, response){
            res.send('html');
          },
          default: function(res, response){
            res.send('default');
          }
        }
      }));
Request Methods
  • req.continueOrError(err, next)

    Check the request for errors using either express-validator methods or pass your own custom errors as the first parameter. If an error is found, the response will be an Http400Error.

    
    var users = {
      1: {
        books: [
          'Growth Engines',
          'It\'s Not About The F-Stops'
        ]
      },
      2: {
        books: [
          'Design For How People Learn',
          'Smart Information Systems'
        ]
      }
    };
    
    app.get('/api/v1/user/:id/books', function(req,res,next){
      // Do some request validation on `id` parameter.
      req.checkParams('id').isInt();
    
      // Custom validation
      var err;
      if( !users.hasOwnProperty(req.params.id)){
        err = new Error('User does not exist');
      }
    
      // If id is not a number or an error is passed as the first
      // parameter, the error will get returned to the client as
      // 400 status.
      req.continueOrError(err, next);
    });
Response Methods
  • res.shouldContinue(err, data)

    Convenience method that returns true if there is data and there is no error, false otherwise. If you need to check for an error and still do more before actually responding.

    app.get('/api/v1/user/:id/books', function(req,res,next){
      async.parallel({
        user: function(done){
          done(null, {name:'John'});
        },
        book: function(done){
          done(null, {book:'Hello World!'});
        }
      }, function(err, results){
    
        if( res.shouldContinue(err, results)){
    
          var book = results[1].book;
          var user = results[0].name;
    
          var responseData = {
            user: user,
            book: book
          };
    
          res.continueOrError(err, responseData, next);
        }else{
          next(new Error('There was an error.'));
        }
    
      });
    });
  • res.respondIfError(err, next)

    Responds if an error was passed and return true otherwise just return false allowing for further processing inside middleware.

    app.get('/api/v1/user/:id/books', function(req,res,next){
    
      UserModel.findOne({
        _id: req.params.id
      }, function(err, user){
    
        if( !res.respondIfError(err,next)){
          BooksModel.find({
            _id: user.books[0]
          }, function(err, books){
            res.continueOrError(err, books, next);
          });
        }
    
      });
    
    });
  • res.continueOrError(err, data, next)

    Continue onto next matching middleware saving data as res.locals.response or respond with error.

    app.get('/api/v1/users', function(req,res,next){
      UserModel.find()
      .exec(function(err, user){
        res.continueOrError(err, user, next);
      });
    });
  • res.continue(data, next)

    Explicitly continue onto next matching middleware saving data as res.locals.response.

    app.get('/api/v1/users', function(req,res,next){
      UserModel.find()
      .exec(function(err, user){
        res.continueOrError(err, user, next);
      });
    });

DEBUG

Debugging is implemented using the debug module.

$ DEBUG=express-responder npm start

process.env.DEBUG = 'express-responder'

DEPENDENCIES

"Bernard of Chartres used to compare us to [puny] dwarfs perched on the shoulders of giants. He pointed out that we see more and farther than our predecessors, not because we have keener vision or greater height, but because we are lifted up and borne aloft on their gigantic stature." Quoted From

This module is primarily built on:

and all of the other modules that make up these packages.

LICENSE

(The MIT License)

Copyright (c) 20014 Big Mountain Ideas + Innovations <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.