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

copyit

v0.2.0

Published

Declare how data is copied into and out of your middleware.

Downloads

7

Readme

copyit

This module allows you to declare how data will move into and out of your middleware.

Installation

npm install copyit

Usage

Refactoring Hard-coded Assumptions

Let's imagine that we're writing a piece of middleware called getUser. This middleware fetches a User record from the database before passing control to the next piece of middleware. Let's start with something simple:

exports.getUser = function(req, res, next) {
  var id   = req.params.id;

  fetchUserById(id, function(user) {
    req.user = user;
    next();
  });
}

Most of the time, this implementation is fine. But, there are a couple of problems:

  • It always reads the id from req.params.id.
  • It always stores the User instance to req.user.

If your controller needs to break either of these assumptions, then it cannot use the getUser() middleware.

We can fix this by allowing the developers to declare the dataflow behaviors when the middleware is initialized. For example:

var copyit = require('copyit');
var from   = copyit.from,
    to     = copyit.to;

router.get('/users/:userId',

  getUser({
    // Obtain the user's id from req.params.userId
    input:  from("params", "userId"),

    // Save the User instance to req.the_user
    output: to("the_user")
  }),

  function(req, res) {
    // See -- the User was saved to req.the_user
    //        instead of req.user
    res.json(req.the_user);
  }
)

The from and to functions return new functions that get and set values, respectively. These getter and setter functions are then passed into the middleware to manage the dataflow. Therefore, the middleware can be rewritten as follows:

var copyit = require('copyit');
var from   = copyit.from,
    to     = copyit.to;

exports.getUser = function(options) {
  options = options || {}

  // Use the getter / setter functions that were provided
  // by the developer, or fallback to the default behaviors.
  var getId   = req.input  || from("params", "id");
  var setUser = req.output || to("user");

  return function(req, res, next) {
    var id   = getId(req);  // Use the getter to obtain the id
    var user = fetchUserById(id);

    setUser(req, user);     // Use the setter to store the User
    next();
  }
}

Ta-da! Now your middleware's dataflow assumptions are no longer hard-coded! You can rely on the default behaviors most of the time, but you also have the option to override them on an as-needed basis.

Simplified Declaration

Of course, it's a little inconvenient to require the developers to use the copyit library just for minor adjustments to the behaviors. Wouldn't it be nice if they could just do something like this instead?

router.get('/users/:userId',

  getUser({
    // Obtain the user's id from req.params.userId
    input:  "userId",

    // Save the User instance to req.the_user
    output: "the_user"
  }),

  function(req, res) {
    res.json(req.the_user);
  }
)

Well, today is your lucky day -- that actually is possible! We just need to modify our middleware so that it automatically coerces the developer's input into getter and setter functions:

var copyit = require('copyit');
var from   = copyit.from,
    to     = copyit.to;

exports.getUser = function(options) {
  options = options || {}

  // If the developer provided values, then coerce them into
  // getter / setter functions.  Otherwise, return undefined.
  var getId   = from.coerce(req.input, {prefix: "params"})
  var setUser = to.coerce(req.output);

  // If no behavior overrides were provided, then fallback to
  // the default behaviors.
  getId   = getId   || from("params", "id");
  setUser = setUser || to("user")

  return function(req, res, next) {
    var id   = getId(req);  // Use the getter to obtain the id
    var user = fetchUserById(id);

    setUser(req, user);     // Use the setter to store the User
    next();
  }
}

Notice that we specified {prefix: "params"} when invoking from.coerce. The influences the way that from.coerce will convert Strings and Arrays into getter / setter functions. In this particular case, it will append "params" to the front of every lookup path. In other words:

// This:
getUser({
  input:  "userId",
  output: "the_user"
});


// Is equivalent to this:
getUser({
  input:  from("params", "userId"),
  output: to("the_user")
});

What if a developer needs to obtain the user's id from req.body instead of req.params? Simple -- they just need to specify the full path by calling from(...):

getUser({
  input:  from("body", "id"),
  output: "the_user"
});

And that, as they say, is that!