run-io

1.1.0 • Public • Published

run-io

Build Status Coverage Status

A monadic abstraction to encapsulate functions with side-effects. The single target of this super-tiny library is to ease testing of side-effect based code.

Installation

$ npm i run-io

API

lift(fn, [opts])

Turns fn into a yieldable function. opts is optional and can have the following keys:

  • sync - Handles this function synchronously

liftMethod(object, method, [opts])

Turns a object method into a yieldable function. opts is the same as in lift().

Example

liftMethod(Model, 'find');

run(generatorFunction, [done])

Generates a function, which can be called with arguments that get passed to the generatorFunction. If called this function executes the effects, yielded by the generator function.

If you omit the done parameter, run will assume that you pass the callback as the last parameter to the result function.

Example

function *gen(req, res) {
  const send = liftMethod(res, 'send', { sync: true });
  yield send({ ok: true });
}
 
function done(err) {
  if (err) throw err;
  console.log('done');
}
 
http.createServer(run(gen, done));

Usage

const io = require('run-io');
 
const lift = io.lift;
const liftMethod = io.liftMethod;
const run = io.run;
 
const getUser = () => {
  // Stuff ...
};
 
const getUserArticles = () => {
  // Stuff ...
};
 
/**
 * Some http handler which performs heavy IO.
 */
function *heavyIO(req, res) {
  const user = yield lift(getUser)();
  const send = liftMethod(res, 'send', { sync: true });
  let articles;
  try {
    articles = yield lift(getUserArticles)(user._id);
  } catch (e) {
    yield send('Error fetching articles!');
    return;
  }
  yield send(articles);
}
 
/**
 * A smoke test for the handler. Notice how we don't even need an
 * implementation of the `getUser()` and `getUserArticles()` methods.
 */
function test() {
  const req = {};
  const res = { send: () => {} }; // eslint-disable-line
 
  // Just fun to test. No database setup needed.
  const user = { _id: 3 };
  const articles = [{ title: 'foo' }];
  const send = liftMethod(res, 'send', { sync: true });
 
  const it = heavyIO(req, res);
  t.deepEqual(it.next().value, lift(getUser)());
  t.deepEqual(it.next(user).value, lift(getUserArticles)(user._id));
  t.deepEqual(it.next(articles).value, send(articles));
}
 
test();
 
// Run the handler.
http.createServer(run(heavyIO, error));
 
function error() {
  // Error handling ...
}

Readme

Keywords

none

Package Sidebar

Install

npm i run-io

Weekly Downloads

0

Version

1.1.0

License

ISC

Last publish

Collaborators

  • domachine