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

http-responses

v0.0.5

Published

Middleware for standardizing the way you send HTTP response statuses.

Downloads

32

Readme

http-responses

NPM Version NPM Download

Middleware for standardizing the way you send HTTP response statuses.

Prevents inconsistencies in your code by standardizing the way you handle sending HTTP response statuses and bodies.

Without http-responses
res.status(401)
res.send(401, body)
res.json(401, body)
next({ status: 401, message: body })
next({ code: 401, message: body })
next(401)
With http-responses
// WWW Response
return next(new res.Unauthorized(body))

// API response
return next(new res.Unauthorized({
  body: body
});

Install

$ npm install http-responses

Express.js, before routing

app.use(require('http-responses'))

Usage Example

Semi-real world example, fetching specific user w/ identifier key for an API.

app.use('/:id', function (req, res, next) {
  if (!req.param('id', false)) {
    return next(new res.Conflict({
      body: 'Id is required.'
    }));
  }

  User.find({ _id: req.param('id') }).then(function (user) {
    if (user) {
      return res.ok('User', user.toJSON(), true);
    }

    return next(new res.NotFound({
      body: 'User does not exist'
    }));
  }).then(function (err) {
    if (err) {
      next(new res.InternalServerError({
        body: err.message
      }));
    }
  });
});

Express Error Handler

Handling errors in express should be done the correct way by defining a middleware that contains an arity of four by including the error argument after your routing has been done. By doing this, anything passed through the next argument will be sent here and we can determine what to do from there, here is a generic example of supporting both API / WWW errors.

var xml = require('js2xmlparser');

app.use(function (err, req, res, next) {
  res.status(err.status);

  if (typeof err.message === 'object') {
    return res.format({
      json: function () {
        res.json({
          code: err.code,
          message: err.message.body
        })
      },

      html: function () {
        res.set('Content-Type', 'application/xml').send(
          xml(err.message.type || 'ApiError', {
            code: err.code,
            message: err.message.text
          })
        );
      }
    });
  }

  res.format({
    json: function () {
      res.json({
        code: err.code,
        message: err.message
      });
    },

    html: function () {
      res.render('error/index', {
        status: err.status,
        code: err.code,
        message: err.message
      });
    }
  });
});

Api

Informational Methods

  • 100: res.Continue()
  • 101: res.SwitchingProtocols(String protocols)
  • 102: res.Processing()

Success Methods

  • 200: res.ok(String view, Mixed body, Boolean api)

    view (WWW: partials/user/profile / API: "User")

    WWW view path / API XML object type.

    Can be omitted when api is false, HTML requests will return text/plain body as no view is declared.

    body (user.toJSON())

    Response body, here we retrieve the user json output

    api (true)

    Determines whether view is an HTML template path or an XML object property <User></User>

    You can also pass a method that will be invoked if you want to resolve formats yourself:

      res.ok(function () {
        res.json(user.toJSON());
      })
  • 204: res.NoContent()

Redirect Methods

  • 300: res.redirect - native express method.
  • 301: res.MovedPermanently(location)
  • 302: res.Found(location)
  • 307: res.TemporaryRedirect(location)
  • 308: res.PermanentRedirect(location)

Error Methods

Properties

code - optional, sub status-code (iis style); defaults to status code.

message - required, mixed type can be string, object, number, date, etc...

Methods

  • 400: new res.BadRequest([code, ]message)
  • 401: new res.Unauthorized([code, ]message)
  • 402: new res.PaymentRequired([code, ]message)
  • 403: new res.Forbidden([code, ]message)
  • 404: new res.NotFound([code, ]message)
  • 405: new res.MethodNotAllowed([code, ]message)
  • 406: new res.NotAcceptable([code, ]message)
  • 407: new res.ProxyAuthenticationRequired([code, ]message)
  • 408: new res.RequestTimeout([code, ]message)
  • 409: new res.Conflict([code, ]message)
  • 411: new res.LengthRequired([code, ]message)
  • 412: new res.PreconditionFailed([code, ]message)
  • 413: new res.PayloadTooLarge([code, ]message)
  • 414: new res.URITooLong([code, ]message)
  • 415: new res.UnsupportedMediaType([code, ]message)
  • 416: new res.RangeNotSatisfied([code, ]message)
  • 417: new res.ExpectationFailed([code, ]message)
  • 418: new res.ImATeapot([code, ]message)
  • 423: new res.Locked([code, ]message)
  • 428: new res.PreconditionRequired([code, ]message)
  • 429: new res.TooManyRequests([code, ]message)
  • 500: new res.InternalServerError([code, ]message)
  • 501: new res.NotImplemented([code, ]message)
  • 502: new res.BadGateway([code, ]message)
  • 503: new res.ServiceUnavailable([code, ]message)
  • 504: new res.GatewayTimeout([code, ]message)
  • 505: new res.HTTPVersionNotSupported([code, ]message)
  • 507: new res.InsufficientStorage([code, ]message)
  • 508: new res.LoopDetected([code, ]message)
  • 510: new res.NotExtended([code, ]message)
  • 511: new res.NetworkAuthenticationRequired([code, ]message)

Special Methods

  • 426: res.UpgradeRequired(String protocols,[code, ]message)

Supported Frameworks

License

MIT