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

thunkify-object

v0.2.0

Published

Build full object wrappers that convert regular node methods into methods that return a thunk

Downloads

80

Readme

thunkify-object

NPM version MIT License Build Status Test Coverage

Build full object wrappers that convert regular node methods into methods that return a thunk, useful for generator-based flow control such as co.

Table of content

Installation

$ npm install thunkify-object --save

Examples

Basic

Let's say you have a constructor with async prototypes using callbacks.

function Dummy() {}

Dummy.prototype.hello = function(callback) {
  setImmediate(callback, null, 'Hello');
}

Dummy.prototype.helloYou = function(you, callback) {
  setImmediate(callback, null, 'Hello ' + you);
}

You first need to create the wrapper constructor once for all future instances.

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var DummyWrapper = new WrapperBuilder()
  .add(['hello', 'helloYou'])
  .getWrapper();

Let's use it with co.

var co = require('co');

co(function* () {
  // Instantiate your wrapper with an instance of the original
  var dummy = new DummyWrapper(new Dummy());

  var a = yield dummy.hello();
  console.log(a); // 'Hello'

  var b = yield dummy.helloYou('World');
  console.log(b); // 'Hello World'
});

Pass Through

If you want some functions not to change their behavior, you can use addPassThrough to simply inherit the function in your wrapper. This is usefull for synchronous functions that doesn't use callback.

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var DummyWrapper = new WrapperBuilder()
 .add(['hello', 'helloYou'])
 .addPassThrough('helloSync')
 .getWrapper();

Transformations

For complex objects, the WrapperBuilder can apply transformations to callback parameters.

Let's wrap the MongoDB native driver as an example.

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var Collection = new WrapperBuilder()
 .add(['add', 'count', 'findOne'])
 .getWrapper();

var Db = new WrapperBuilder()
  .add('collection', {
    transformations: {
      1: function(col) { return new Collection(col); }
    }
  })
  .getWrapper();

var MongoClient = new WrapperBuilder()
  .add('connect', {
    transformations: {
      1: function(db) { return new Db(db); }
    }
  })
  .getWrapper();

Now that you have your wrappers, you can use them like that.

var mongodb = require('mongodb');

function* foo(url) {
  var mongoClient = new MongoClient(mongodb.MongoClient);

  // returned db is a wrapper
  var db = yield mongoClient.connect(url);

  // returned collection is a wrapper
  var collection = yield db.collection('documents');

  yield collection.add({ _id: 1, name: 'Paul Valery' });
  return yield collection.findOne({ _id: 1 });
}

Let's use it with co.

var co = require('co');

co(function* () {
  var doc = yield foo('mongodb://localhost:27017/myproject');
  console.log(doc);
});

Dealing with functions being both async and sync

Sometimes functions have an optional callback parameter (like this MongoDB driver method). That means when you call it with a callback it's async, but when you call it without a callback it's sync (potentially returning a value).

Here is how to wrap those functions.

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var Wrapper = new WrapperBuilder()
 .add('helloWithOptionalCallback', {
   sync: true
 })
 .getWrapper();

Any wrapper instance will have 2 explicit methods:

  • helloWithOptionalCallback which is async, returning a thunk
  • helloWithOptionalCallbackSync which is sync (note the Sync suffix)

The synchronous prototype can be customized with a specific name format and a transformation.

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var Wrapper = new WrapperBuilder()
 .add('helloWithOptionalCallback', {
   sync: {
     prototypeNameFormat: '%sCustomSuffix',
     transformation: function(res) {
       return res;
     }
   }
 })
 .getWrapper();

Events

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var Wrapper = new WrapperBuilder()
 .addEvent(['on', 'once'])
 .addPassThrough('emit')
 .getWrapper();
var EventEmitter = require('events').EventEmitter;
var co = require('co');

co(function* () {

  var e = new Wrapper(new EventEmitter());

  setTimeout(function() {
    e.emit('finish', 'Finish data');
  }, 200);


  var res = yield e.on('finish');
  console.log(res); // 'Finish data'
});

Note that you can still pass a listener as a callback:

var EventEmitter = require('events').EventEmitter;
var co = require('co');

co(function* () {

  var e = new Wrapper(new EventEmitter());

  setTimeout(function() {
    e.emit('finish', 'Finish data');
  }, 200);


  e.on('finish', function(res) {
    console.log(res); // 'Finish data'
  });
});

If you need transformations, you can define them for each event:

var WrapperBuilder = require('thunkify-object').WrapperBuilder;

var Wrapper = new WrapperBuilder()
 .addEvent(['on', 'once'], {
   events: {
     'finish': transformations: {
       0: function(arg) { return ... },
       1: function(arg) { return ... }
     }
   }
 })
 .addPassThrough('emit')
 .getWrapper();

Running tests

$ make test

With code coverage.

$ make test-cov

License

Thunkify-object is freely distributable under the terms of the MIT license.