thunkify-object
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
- Examples
- Basic
- Pass Through
- Transformations
- Dealing with functions being both async and sync
- Events
- Running tests
- License
Installation
$ npm install thunkify-object --save
Examples
Basic
Let's say you have a constructor with async prototypes using callbacks.
{} Dummyprototype { ;} Dummyprototype { ;}
You first need to create the wrapper constructor once for all future instances.
var WrapperBuilder = WrapperBuilder; var DummyWrapper = ;
Let's use it with co.
var co = ; ;
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 = WrapperBuilder; var DummyWrapper = ;
Transformations
For complex objects, the WrapperBuilder
can apply transformations to callback parameters.
Let's wrap the MongoDB native driver as an example.
var WrapperBuilder = WrapperBuilder; var Collection = ; var Db = ; var MongoClient = ;
Now that you have your wrappers, you can use them like that.
var mongodb = ; { var mongoClient = mongodbMongoClient; // returned db is a wrapper var db = mongoClient; // returned collection is a wrapper var collection = db; collection; return collection;}
Let's use it with co.
var co = ; ;
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 = WrapperBuilder; var Wrapper = ;
Any wrapper instance will have 2 explicit methods:
helloWithOptionalCallback
which is async, returning a thunkhelloWithOptionalCallbackSync
which is sync (note the Sync suffix)
The synchronous prototype can be customized with a specific name format and a transformation.
var WrapperBuilder = WrapperBuilder; var Wrapper = ;
Events
var WrapperBuilder = WrapperBuilder; var Wrapper = ;
var EventEmitter = EventEmitter;var co = ; ;
Note that you can still pass a listener as a callback:
var EventEmitter = EventEmitter;var co = ; ;
If you need transformations, you can define them for each event:
var WrapperBuilder = WrapperBuilder; var Wrapper = ;
Running tests
$ make test
With code coverage.
$ make test-cov
License
Thunkify-object is freely distributable under the terms of the MIT license.