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

promesso

v5.0.0

Published

Opinionated Promise handler for express.js 4.x

Downloads

19

Readme

promesso

NPM Build Status

Opinionated Promise handler for express.js 4.x

Promess-o wraps a Promise-based middleware with different error handlers and converts it to a simple function (actually an array of functions) to be used by express

Status: Tested, production uptime medium.

Install

Install in your project using: npm i --save promesso

Example

An Express middleware can be declared like this:

const XError = require('x-error');

function myValidator (req) {
  if (!req.body.creditcard)
    throw new XError(801).m('creditcard is required').hc(403);
}

function exmplMiddleware (req) {
  return Promise.resolve({ status: 'ok', data: req.body.creditcard });
}
module.exports = [myValidator, exmplMiddleware];

In this sample middleware the main functions is asynchronous and requires a specific req.body.creditcard otherwise it cannot function properly.

promesso will wrap exmplMiddleware with myValidator using express middleware Array notation.

This is the corrisponding express.js vanilla code

function myValidator (req, res, next) {
  if (!req.body.creditcard) next('creditcard is required');
  else next();
}

function exmplMiddleware (req, res) {
  Promise.resolve({ status: 'ok', data: req.body.creditcard })
    .then(function (data) {
      res.send(data);
    });
}

function errorHandler (err, req, res) {
  if (err) res.status(403).send(err);
}

module.exports = [myValidator, exmplMiddleware];

Here there are tricky next() calls to remember and Error(s) are not class-based.

API

promesso.logger([loggingFn], [errorFn])

Changes standard console.log and console.error functions to output informations;

promesso(Function|Function[])

Promesso can receive a single function or an array of ordered functions. All the functions will be promisified unless they have a @raw = true annotation. The functions will call next() when the promise is completed, the last one calls res.send() appropriately.

Synchronous returns

If you need to return a static template of some kind you can just return it, promesso will handle it gracefully.

function webpage (req) {
  return `
    <html>
      <head></head>
      <body><h1>Hello World</h1></body>
    </html>
  `;
}

Raw Functions

Sometime you might need a raw express function, in this case you can use the handler['@raw'] = true annotation.

function rawHandler (req, res, next) {
  if (req.accepts('html')) return next();
  res.sendFile('welcome-logo.png');
}
rawHandler['@raw'] = true;

function webpage (req) {
  return Promise.resolve(`<html><body><h1>Hello World</h1></body></html>`)
}

module.exports = [rawHandler, webpage];

Custom res methods using Promises

It can happen that is required to give a response with a webpage res.render(...) or give multiple commands, like res.set(...).

In that case the Promise should be resolved with a Function having as first parameter the req node/express object

Example:

function customResponseMiddleware (req) {
  var variableInClosure = 55;
  return Promise.resolve(customFn);

  function customFn (res) {
    res.set('Content-Type', 'text/plain');
    res.send({ message: 'everything ok', variable: variableInClosure });
  }
}

Altough a bit verbose, the implementation is very simple, it's just a sequence of res[method].apply(res, r.args) calls, it's not tought to be used often.

TODO

  • example directory, with full Express 5.x example

Roadmap

  • Possibility to extend with another type of errors (?)
  • Remove express-validation from dependencies - #1

Changelog

[5.0.0] - 2016-07-19

Changes

  • Response handled by promess-o middlewares are now any type, except functions. If returned a function, it would be a custom response handler. More flexible and concise.

[4.0.0] - 2016-06-09

Changes

  • Changed the way the library works, handles Array of middlewares, automatically handles next() calls

[3.0.0] - 2016-05-19

Changes

  • XErrors httpResponse gets converted to a JSON response { code: 1xx, message: 'error message' } in case is a plain string

[2.0.1] - 2016-05-13

Changes

  • Uniformed loggingFn calls to ([obj], message) to support pino / bunyan
  • errorFn calls are still all string-based, it's used for unknown-type of errors

[2.0.0] - 2016-05-11

Added

  • Tests!

Changes

  • Some erroneous calls in the code

[1.1.0] - 2016-05-03

Added

  • promesso.logger to customize the logging/error functions