Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

node-switchback

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

node-switchback - npm Package Compare versions

Comparing version 0.1.0 to 0.1.1

.editorconfig

10

lib/constants.js
module.exports = {
// Used to identify a function as a switchback.
telltale: {
key: '_TELLTALE',
value: 'a94hgd9gal2gl2bmc,=1aga'
}
// Used to identify a function as a switchback.
telltale: {
key: '_TELLTALE',
value: 'a94hgd9gal2gl2bmc,=1aga'
}
};

@@ -41,3 +41,7 @@ /**

// Mix in non-enumerable `.inspect()` method
Object.defineProperty(this, 'inspect', { enumerable: false, writable: true });
_switch.inspect = function () { return '[Switchback]'; };
return _switch;
};
};

@@ -50,6 +50,6 @@ /**

callback = {
error: function (err) {
error: function(err) {
Switchback.emit('error', err);
},
success: function (/*...*/) {
success: function( /*...*/ ) {
Switchback.emit.apply(e, ['success'].concat(Array.prototype.slice.call(arguments)));

@@ -143,2 +143,2 @@ }

module.exports = switchback;
module.exports = switchback;

@@ -12,39 +12,39 @@ /**

/**
* `normalize.callback( callback )`
*
* If `callback` is provided as a function, transform it into
* a "Switchback Definition Object" by using modified copies
* of the original callback function as error/success handlers.
*
* @param {Function|Object} callback [cb function or switchback def]
* @return {Object} [switchback def]
*/
callback: function _normalizeCallback (callback, callbackContext) {
/**
* `normalize.callback( callback )`
*
* If `callback` is provided as a function, transform it into
* a "Switchback Definition Object" by using modified copies
* of the original callback function as error/success handlers.
*
* @param {Function|Object} callback [cb function or switchback def]
* @return {Object} [switchback def]
*/
callback: function _normalizeCallback(callback, callbackContext) {
if (_.isFunction(callback)) {
var _originalCallbackFn = callback;
callback = {
success: function() {
// Shift arguments over (prepend a `null` first argument)
// so this will never be perceived as an `err` when it's
// used as a traditional callback
var args = Array.prototype.slice.call(arguments);
args.unshift(null);
_originalCallbackFn.apply(callbackContext || this, args);
},
error: function() {
// Ensure a first arg exists (err)
// (if not, prepend an anonymous Error)
var args = Array.prototype.slice.call(arguments);
if (!args[0]) {
args[0] = new Error();
}
_originalCallbackFn.apply(callbackContext || this, args);
}
};
callback = callback || {};
}
return callback;
}
if (_.isFunction(callback)) {
var _originalCallbackFn = callback;
callback = {
success: function() {
// Shift arguments over (prepend a `null` first argument)
// so this will never be perceived as an `err` when it's
// used as a traditional callback
var args = Array.prototype.slice.call(arguments);
args.unshift(null);
_originalCallbackFn.apply(callbackContext || this, args);
},
error: function() {
// Ensure a first arg exists (err)
// (if not, prepend an anonymous Error)
var args = Array.prototype.slice.call(arguments);
if (!args[0]) {
args[0] = new Error();
}
_originalCallbackFn.apply(callbackContext || this, args);
}
};
callback = callback || {};
}
return callback;
}
};
{
"name": "node-switchback",
"version": "0.1.0",
"version": "0.1.1",
"description": "Normalize callback fns to switchbacks and vice versa",

@@ -31,4 +31,5 @@ "main": "lib/index.js",

"devDependencies": {
"should": "~2.1.1"
"should": "~2.1.1",
"mocha": "~1.18.2"
}
}

@@ -1,18 +0,36 @@

switchback
========
# [<img title="switchback - Delinearizes flow control into a more realistic directed graph" src="http://i.imgur.com/Jgrc9k2.png" width="75px" alt="image of a mountain switchback"/>](https://github.com/balderdashy/switchback) Switchback
[![Bower version](https://badge.fury.io/bo/switchback.png)](http://badge.fury.io/bo/switchback)
[![NPM version](https://badge.fury.io/js/node-switchback.png)](http://badge.fury.io/js/node-switchback) &nbsp; &nbsp;
[![Build Status](https://travis-ci.org/balderdashy/switchback.svg?branch=master)](https://travis-ci.org/balderdashy/switchback)
Normalize a callback to a "switchback" and vice versa.
+ Allows your functions to "branch".
+ Makes usage of branching functions suck less.
+ Maintains 100% compatibility with node callbacks.
+ Helps keep users of your async functions from "forgetting to return early" andthentimespaceparadox
+ Allows your functions to **"[b](http://en.wikipedia.org/wiki/Branch_table)[r](http://en.wikipedia.org/wiki/Monad_(functional_programming))[a](http://www.afralisp.net/autolisp/tutorials/cond-vs-if.php)[n](http://en.wikipedia.org/wiki/Dispatch_table)[ch](http://en.wikipedia.org/wiki/Virtual_method_table)"**.
+ Makes usage of branching functions **suck less**.
+ Maintains **100% compatibility** with [node callbacks](http://nodeguide.com/style.html#callbacks).
+ Helps keep users of your async functions from "forgetting to return early" **andthentimespaceparadox**
+ Works w/ Node.js and in the browser.
+ [Table the label, wear your own name.](http://news.moviefone.com/2010/05/26/cheesy-mr-t-clip-advises-you-to-table-the-label/)
> You might be familiar with a simlar concept from `jQuery.ajax` (i.e. `$.ajax({ success: foo, error: bar });`)
========================================
## Contents
| | Jump to... |
|-----|-------------------------|
| I | [Usage for Users](#using-a-function-with-a-switchback)
| II | [Usage for Implementors](#implementing-a-function-with-a-switchback)
| III | [Usage w/ Other Flow Control Libraries](#using-switchbacks-with-other-flow-control-libraries)
| IV | [Details](#details)
| V | [License](#license)
========================================
## Usage
##### Using a function with a switchback
### Using a function with a switchback
```javascript

@@ -25,3 +43,3 @@

// Let's try it!
// Let's try it!

@@ -33,3 +51,3 @@ // Pass in a switchback:

// (i.e. its only purpose is to act as a catch-all if the two explicit handlers are not specified)
gasolineExplosion: function () {

@@ -50,6 +68,6 @@ // Safety goggles next time.

// Handle the error, count fingers to figure out what happened, etc.
// Also don't forget to returnearly or use `else` or something.
// Also don't forget to return early or use `else` or something.
return;
}
// Lawn was mowed, everything worked.

@@ -59,6 +77,49 @@ });

// Both are cool.
// Finally, it's worth noting that the return value is an EventEmitter:
mowLawn('quickly', 'zigzags')
.on('gasolineExplosion', function (err) {
// Safety goggles next time.
})
.on('sliceOffFinger', function (numFingersLost) {
// Oh my.
})
.on('success', function (dollarsEarned) {
// Lawn was mowed, everything worked.
})
```
##### Writing a function that takes advantage of switchbacks
### Implementing a function with a switchback
Adding an optional switchback interface to a function is pretty simple. Just install:
```sh
$ npm install node-switchback --save
```
Require:
```js
var switchback = require('node-switchback');
```
And then call `switchback()` on the callback at the top of your function, overriding the original value:
```javascript
cb = switchback(cb);
```
To enable complete, chainable usage, you should also return the switchback from your function:
```javascript
return cb;
```
For example:
```javascript
var switchback = require('node-switchback');

@@ -69,11 +130,11 @@

// that's it!
// All the standard callback things work the same
if (err) return cb(err);
// But now you can call custom handlers too:
if (cb.someHandler) {
}
// Mix it up!

@@ -83,2 +144,5 @@ // Table the label!

cb(null, 'whatever', 'you', 'want');
// Make it chainable
return cb;
}

@@ -89,5 +153,10 @@

========================================
## Details
Switchback is a JavaScript flow control library. It works alongside async, promises, generators, and conventional Node callbacks to provide support for error negotiation via casefunctions. It also makes your callbacks EventEmitters. You might be familiar with a similar concept from `jQuery.ajax` (i.e. `$.ajax({ success: foo, error: bar });`). It may be helpful to think about this module as the equivalent of something like `async.if()` or `async.switch()`.
##### More examples of exactly what to expect

@@ -101,10 +170,10 @@

cb = switchback(cb);
// Do your stuff
// ...
// If cb was a switchback:
/////////////////////////////////////////////////
// Things that trigger the `success` handler:

@@ -115,4 +184,4 @@ return cb();

return cb.success();
// Things that trigger the `error` handler:

@@ -122,7 +191,7 @@ return cb('bahh!');

return cb.error();
// If cb was a callback function:
/////////////////////////////////////////////////
// OK but what about usage with normal node callbacks?

@@ -133,3 +202,3 @@ //

// will get printed to the console in each case:
cb() // ---> null undefined

@@ -139,3 +208,3 @@ cb(null, 'the results!!!!') // ---> null the results!!!!

cb.success('the results!!!!'); // ---> null the results!!!!
cb('bahh!') // ---> bahh! undefined

@@ -157,3 +226,3 @@ cb('bahh!', 'foo') // ---> bahh! foo

}
// Pets were freed, we can go about our business

@@ -175,5 +244,5 @@ });

========================================
## Using switchbacks with other flow control libraries

@@ -195,1 +264,18 @@

```
========================================
## License
**[MIT](./LICENSE)**
&copy; 2014
[Mike McNeil](http://michaelmcneil.com), [Balderdash](http://balderdash.co) & contributors
This module is free and open-source under the [MIT License](http://sails.mit-license.org/).
![image_squidhome@2x.png](http://i.imgur.com/RIvu9.png)
[![githalytics.com alpha](https://cruel-carlota.pagodabox.com/a22d3919de208c90c898986619efaa85 "githalytics.com")](http://githalytics.com/balderdashy/switchback)

@@ -0,18 +1,20 @@

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var should = require('should');
var EventEmitter = require('events').EventEmitter;
var switchback = require('../lib');
// Set up event bus to provide access to callback/switchback handler outcomes
var Bus = function () {
this.afterFixture = function (fixtureID, cbOutcome, fnToCall) {
return Bus.once(fixtureID, function (_outcome) {
// cbOutcome should be an empty object at this point (passed by reference)
cbOutcome.args = _outcome.args;
cbOutcome.ctx = _outcome.ctx;
fnToCall();
});
};
var Bus = function() {
this.afterFixture = function(fixtureID, cbOutcome, fnToCall) {
return Bus.once(fixtureID, function(_outcome) {
// cbOutcome should be an empty object at this point (passed by reference)
cbOutcome.args = _outcome.args;
cbOutcome.ctx = _outcome.ctx;
fnToCall();
});
};
};
require('util').inherits(Bus, EventEmitter);
util.inherits(Bus, EventEmitter);
Bus = new Bus();

@@ -23,13 +25,13 @@

fn: function () {
// Sniff call/caller data from this callback function by emitting event on cbReporter
Bus.emit('fn', {
args: Array.prototype.slice.call(arguments),
ctx: this
});
},
handlers: {
success: function (data) {},
error: function (err) {}
}
fn: function() {
// Sniff call/caller data from this callback function by emitting event on cbReporter
Bus.emit('fn', {
args: Array.prototype.slice.call(arguments),
ctx: this
});
},
handlers: {
success: function(data) {},
error: function(err) {}
}
};

@@ -39,106 +41,100 @@

// Suites
describe('switchback(Function)', function (){
var sb;
var cb = fixtures.fn;
describe('switchback(Function)', function() {
it('should return a switchback', function () {
sb = switchback(cb);
sb.should.be.a.Function;
(switchback.isSwitchback(sb)).should.be.ok;
});
var sb;
var cb = fixtures.fn;
it('should return a switchback', function() {
sb = switchback(cb);
sb.should.be.a.Function;
(switchback.isSwitchback(sb)).should.be.ok;
});
describe('when calling returned switchback as sb(null, 14, 23),', function () {
var cbOutcome = {};
_listenForCallback(cbOutcome, function () {
sb(null, 14, 23);
});
describe('when calling returned switchback as sb(null, 14, 23),', function() {
var cbOutcome = {};
_listenForCallback(cbOutcome, function() {
sb(null, 14, 23);
});
_testThatCallbackHasNoError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
_testThatCallbackHasNoError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
describe('when calling returned switchback as sb("some error", 14, 23),', function() {
var cbOutcome = {};
_listenForCallback(cbOutcome, function() {
sb('some error', 14, 23);
});
describe('when calling returned switchback as sb("some error", 14, 23),', function () {
var cbOutcome = {};
_listenForCallback(cbOutcome, function () {
sb('some error', 14, 23);
});
_testThatCallbackHasError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
_testThatCallbackHasError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
describe('when calling returned switchback as sb.error("some error", 14, 23),', function() {
var cbOutcome = {};
_listenForCallback(cbOutcome, function() {
sb.error('some error', 14, 23);
});
_testThatCallbackHasError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
describe('when calling returned switchback as sb.error(),', function() {
var cbOutcome = {};
_listenForCallback(cbOutcome, function() {
sb.error();
});
describe('when calling returned switchback as sb.error("some error", 14, 23),', function () {
var cbOutcome = {};
_listenForCallback(cbOutcome, function () {
sb.error('some error', 14, 23);
});
_testThatCallbackHasError(cbOutcome);
});
_testThatCallbackHasError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
describe('when calling returned switchback as sb.error(),', function () {
var cbOutcome = {};
_listenForCallback(cbOutcome, function () {
sb.error();
});
_testThatCallbackHasError(cbOutcome);
});
describe('when calling returned switchback as sb.success("should not be an error", 14, 23),', function() {
var cbOutcome = {};
_listenForCallback(cbOutcome, function() {
sb.success('should not be an error', 14, 23);
});
_testThatCallbackHasNoError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
describe('when calling returned switchback as sb.success(),', function() {
var cbOutcome = {};
_listenForCallback(cbOutcome, function() {
sb.success();
});
_testThatCallbackHasNoError(cbOutcome);
});
});
describe('when calling returned switchback as sb.success("should not be an error", 14, 23),', function () {
var cbOutcome = {};
_listenForCallback(cbOutcome, function () {
sb.success('should not be an error', 14, 23);
});
_testThatCallbackHasNoError(cbOutcome);
_testThatOtherArgumentsExist(cbOutcome);
});
describe('when calling returned switchback as sb.success(),', function () {
var cbOutcome = {};
_listenForCallback(cbOutcome, function () {
sb.success();
});
_testThatCallbackHasNoError(cbOutcome);
});
describe('switchback(Handlers)', function() {
});
describe('switchback(Function, Object)', function() {
describe('switchback(Handlers)', function (){
});
describe('switchback(Function, Object)', function (){
});
describe('switchback(Handlers, Object)', function() {
describe('switchback(Handlers, Object)', function (){
});
describe('switchback(Function, Object, Object)', function (){
});
describe('switchback(Function, Object, Object)', function() {
describe('switchback(Handlers, Object, Object)', function (){
});
describe('switchback(Handlers, Object, Object)', function() {
});

@@ -148,38 +144,38 @@

// Helpers
function _testThatCallbackHasError (cbOutcome) {
it('should NOT receive error argument in original cb function', function () {
should(cbOutcome.args).be.ok;
should(cbOutcome.ctx).be.ok;
cbOutcome.args.should.be.an.Array;
cbOutcome.args.length.should.be.above(0);
should(cbOutcome.args[0]).be.ok;
});
function _testThatCallbackHasError(cbOutcome) {
it('should NOT receive error argument in original cb function', function() {
should(cbOutcome.args).be.ok;
should(cbOutcome.ctx).be.ok;
cbOutcome.args.should.be.an.Array;
cbOutcome.args.length.should.be.above(0);
should(cbOutcome.args[0]).be.ok;
});
}
function _testThatCallbackHasNoError (cbOutcome) {
it('should NOT receive error argument in original cb function', function () {
should(cbOutcome.args).be.ok;
should(cbOutcome.ctx).be.ok;
cbOutcome.args.should.be.an.Array;
should(cbOutcome.args[0]).not.be.ok;
});
function _testThatCallbackHasNoError(cbOutcome) {
it('should NOT receive error argument in original cb function', function() {
should(cbOutcome.args).be.ok;
should(cbOutcome.ctx).be.ok;
cbOutcome.args.should.be.an.Array;
should(cbOutcome.args[0]).not.be.ok;
});
}
function _testThatOtherArgumentsExist (cbOutcome) {
it('should receive the two subsequent arguments in original cb function', function () {
should(cbOutcome.args).be.ok;
should(cbOutcome.ctx).be.ok;
cbOutcome.args.should.be.an.Array;
cbOutcome.args.length.should.be.above(1);
should(cbOutcome.args[1]).be.ok;
should(cbOutcome.args[2]).be.ok;
});
function _testThatOtherArgumentsExist(cbOutcome) {
it('should receive the two subsequent arguments in original cb function', function() {
should(cbOutcome.args).be.ok;
should(cbOutcome.ctx).be.ok;
cbOutcome.args.should.be.an.Array;
cbOutcome.args.length.should.be.above(1);
should(cbOutcome.args[1]).be.ok;
should(cbOutcome.args[2]).be.ok;
});
}
function _listenForCallback (cbOutcome, fnThatRunsCallback) {
before(function (done) {
// When callback fires, proceed
Bus.afterFixture('fn', cbOutcome, done);
fnThatRunsCallback();
});
}
function _listenForCallback(cbOutcome, fnThatRunsCallback) {
before(function(done) {
// When callback fires, proceed
Bus.afterFixture('fn', cbOutcome, done);
fnThatRunsCallback();
});
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc