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-bifrost

v0.0.4

Published

Bridges the HTTP world (Express middleware) to the pure controller world

Downloads

10

Readme

express-bifrost

Decouples the HTTP world (Express middleware) from the rest of your code so that HTTP concerns don't leak between them. Actually, express-bifrost doesn't do the decoupling itself, but provides a pattern to encourage you to do it.

Thor wades while the æsir ride by Frølich

As analogies that are pushed too far for the sake of a catchy name go:

Bifröst is a burning rainbow bridge that reaches between Midgard (Earth) and Asgard, the realm of the gods.

Usage

Install from npm: npm install express-bifrost or yarn add express-bifrost

Include in your code:

const bifrost = require('express-bifrost');

or

import bifrost from 'express-bifrost';

Where you would typically pass the Request and Response objects of Express directly down to a controller, use express-bifrost as a bridge between the HTTP Request/Response objects and an HTTP-agnostic controller. express-bifrost acts as a factory for Express middleware.

Before:

// Controller directly knows about HTTP Request/Response
function readHorse(req, res, next) {
  const horseId = req.params.horseId;

  Horse
    .findById(horseId)
    .then(horse => {
      if (horse) {
        res.json(horse)
      } else {
        res.status(404).send('Horse not found');
      }
    })
    .catch(next);
}

app.get('/horses/:horseId', readHorse);

After:

// Controller is HTTP-agnostic -- just returns a Promise
function readHorse(horseId) {
  return Horse
    .findById(horseId)
    .then(horse => {
      if (horse) {
        return horse;
      } else {
        throw new Error('Horse not found');
      }
    });
}

app.get('/horses/:horseId', bifrost(req => {
  // Collect everything we need from the Request
  const horseId = req.params.horseId;

  // Pass on to non-HTTP land
  return readHorse(horseId);
});

// Or, super-compact version:
app.get('/horses/:horseId', bifrost(req => readHorse(req.params.horseId));

By default, express-bifrost sends the promise resolution value as the response using .send(), which will automatically send objects as JSON. Also, promise rejection values (errors) are passed down to other middleware through next(). When you need fine-grained control over how responses are sent, and how errors are handled, you can use the extended syntax and pass express-bifrost an object with req, res and err properties, which are all optional:

app.get('/horses/:horseId', bifrost({
  req: req => readHorse(req.params.horseId),
  res: (res, data) => {
    // Wrap the response returned from the request handler inside an envelope
    res.json({
      meta: { horseId },
      data
    });
  },
  err: (res, next, error) => {
    if (/not found/i.test(error.message)) { // Note: Hacky! Just OK for the sake of this example.
      // Be nice and return a 404
      res.status(404).send(error.message);
    } else {
      // Pass down to other middleware / default error handling
      next(error);
    }
  }
});

API

Actually, the implementation of express-bifrost is so tiny, you might be better off just reading the entire source.

Options

express-bifrost takes a single argument which is either an Object or a Function. The Function flavour acts as a shorthand for the Object flavour with just the req property. The following two forms are functionally identical:

bifrost(req => fetchMySword(req.params.urgency))

bifrost({
  req: req => fetchMySword(req.params.urgency)
})

The Object flavour expects the following properties:

req

Function, optional. The request handler. This should be a function that takes an Express Request object instance. Its purpose should be to grab whatever is needed from the request object and pass it down to controller/service layers in your application. The function may return a Promise. It may also return a value to be returned in the response or throw an exception to trigger error handling.

Examples:

bifrost({
  req: req => {
    return authenticate(req.body.username, req.body.password); // returns a Promise
  }
})

bifrost({
  req: req => {
    if (isAuthenticated(req.body.username, req.body.password)) { // returns a Boolean
      return 'Yay!';
    } else {
      throw new Error('Nay!');
    }
  }
})

res

Function, optional. The response handler. This should be a function that takes an Express Response object and the data returned from the request handler (undefined if no response handler was provided). The function takes over express-bifrost's default response handling of sending whatever was returned by the request handler via the Response object's .send() method.

Example:

bifrost({
  req: req => collateDashboardData(),
  res: (res, data) => res.render('dashboard', data)
})

err

Function, optional. The error handler. This should be a function that takes an Express Response object, the Express next callback handler, and an error value. The function takes over express-bifrost's default error handling of passing the error value down to the Express next callback. You can use this to apply custom error handling depending on the error value and respond with the appropriate HTTP response codes.

Example:

bifrost({
  err: (res, next, error) => {
    // Handle custom errors thrown by the controller
    if (error instanceof AuthorizationError) {
      res.status(403).end();
    } else if (error instanceof ResourceNotFoundError) {
      res.status(404).end();
    } else {
      next(error);
    }
  }
})

Defaults

The defaults property of express-bifrost holds default values for the options above. All default options are set to null by default. Override any of these properties to have global handlers that are applied across all express-bifrost middleware instances.

Example:

// Generic response handler
bifrost.defaults.res = (res, data) => {
  if (data instanceof File) {
    res.sendFile(data.path);
  } else {
    res.json(data);
  }
};

// Generic error handler
bifrost.defaults.err = (res, next, error) => {
  if (error instanceof AuthorizationError) {
    res.status(403).end();
  } else if (error instanceof ResourceNotFoundError) {
    res.status(404).end();
  } else if (error instanceof BadArgumentsError) {
    res.status(400).end();
  } else {
    res.status(500).end();
  }
};

License

MIT

Credits

Inspired by fxrm-action, written by Nick Matantsev.