{"author":{"name":"bradleymeck","email":"bradley.meck@gmail.com"},"name":"understudy","description":"action interceptor for dynamic extensible systems","tags":["hooks","before","after","flow control"],"version":"4.1.0","main":"index.js","repository":{"type":"git","url":"git+ssh://git@github.com/bmeck/understudy.git"},"dependencies":{},"devDependencies":{"accounting":"~0.4.1","benchmark":"~1.0.0","microtime":"^2.0.0"},"optionalDependencies":{},"scripts":{"test":"for SCRIPT in test/*.js; do echo Testing $SCRIPT; node $SCRIPT; done"},"engines":{"node":"*"},"license":"MIT","gitHead":"dc06eac5770435242821a32f685bab91b33004f8","bugs":{"url":"https://github.com/bmeck/understudy/issues"},"homepage":"https://github.com/bmeck/understudy#readme","_id":"understudy@4.1.0","_shasum":"b6d6e9624ccbb7fa2e51969f5be2c748e969ef4a","_from":".","_npmVersion":"2.14.3","_nodeVersion":"4.1.0","_npmUser":{"name":"jcrugzz","email":"jcrugzz@gmail.com"},"maintainers":[{"name":"bradleymeck","email":"bradley.meck@gmail.com"},{"name":"indexzero","email":"charlie.robbins@gmail.com"},{"name":"jcrugzz","email":"jcrugzz@gmail.com"}],"dist":{"shasum":"b6d6e9624ccbb7fa2e51969f5be2c748e969ef4a","tarball":"http://registry-npm.ywwl.com/understudy/download/understudy-4.1.0.tgz","integrity":"sha512-pM7KoFRm92pe6ksswZPbUzJAtwo2aUSkR1W13UaTZ2b6LpLGTZJAiYNZQ4iWX4fES3huZUWP+1E0UUC1b3r+kg==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDDQsiK8y8svbe5Esaf3Y2e8/XapSQFM10jjqgUIMj/+AIgCPdDAX1Mfpv90eDJin5kNuxk2y4GPwm5C0TyLVtKKws="}],"size":8925,"noattachment":false,"key":"/understudy/-/understudy-4.1.0.tgz"},"directories":{},"readme":"# Understudy\n\nA means to provide interceptors (i.e. hooks) when performing asynchronous actions.\n\n* **All hooks are asynchronous**\n* * All logic done by `perform`-based actions is asynchronous.\n* * Error first helpers.\n* * Fail fast.\n* **Consistency in arguments provided to hooks & actions**\n* * Hooks can only mutate arguments that they are passed, not the number of arguments.\n* * Use of callback arguments to pass information removes focus on return values to mitigate this potentially odd behavior.\n* **Opt-in behavior.**\n* * Only calls to `.perform(action ...` enable hooking.\n\n![](assets/flow.png)\n\nBy depending on `understudy` you are exposed to four methods: `perform`, `before`, `after` and `waterfall`\n\n#### `.perform(action, arg0, /* arg1, ... */, work, callback)`\n\nThis is the core API for invoking hooks provided by `Understudy`. Each call to `perform` for the same `action` should have a consistent argument signature because this is what will be expected by each of the before and after hooks for the `action`. The overall flow control is:\n\n1. Call all `before` hooks for `action`.\n2. Call `work` function for `action`.\n3. Call all `after hooks for `action`.\n4. Call `callback` with results from `work` function.\n\n#### `.before(action, arg0, /* arg1, ... */, next)`\n\nCalled before the `work` function is executed in perform with _exactly_ the arguments passed to `.perform`. Nothing passed to `next` have an impact on the flow control above **except any error is supplied short-circuits execution to the callback.**\n\n#### `.after(action, arg0, /* arg1, ... */, next)`\n\nCalled after the `work` function is executed in perform with _exactly_ the\narguments passed to `.perform`. Nothing passed to `next` have an impact on the\nflow control above **except any error is supplied short-circuits execution to\nthe callback.** \n\nWhile the above statement is true when using `.perform`, `after` hooks acquire a\n`waterfall` like behavior with `.waterfall` where the result of work function\ngets passed to the `after` hooks. Each after hook is then able to mutate the\narguments passed to the next one. Strongly discouraged to change number of\narguments for your user's sanity.\n\n#### `.waterfall(action, arg0, /* arg1, ... */, work, callback)`\n\nThis is a slightly different `perform` that is very useful for when you have to\nmodify state received from a function in a sequence of configurable hooks.\n\n1. Call all `before` hooks for `action`.\n2. Call `work` function for `action`.\n3. Call all `after hooks for `action` with the result returned from the `work`\n   function.\n4. Call `callback` with results from the `after` hooks execution (if any) and\n   otherwise the results from the `work` function.\n\n\n## Real-world Usage\n\nLet's consider a real-world application with two interceptable actions:\n\n- `start`: Application has started\n- `http:request`: Application has received an incoming HTTP request.\n\nWe could easily implement this `App` behavior in `Understudy`:\n\n``` js\nvar Understudy = require('understudy');\n\nvar App = module.exports = function App() {\n  Understudy.call(this);\n};\n\n//\n// Starts the application after running before and\n// after hooks.\n//\nApp.prototype.start = function (options, callback) {\n  this.perform('start', options, function (next) {\n    //\n    // Here, `options` may have been mutated from the execution\n    // of the before hooks.\n    // ...\n    // Do some other async thing\n    // ...\n    // These arguments are passed to the final callback unless\n    // short-circuited by an error here, or in an after hook.\n    //\n    next(null, options);\n  }, callback);\n};\n\nApp.prototype.handle = function (req, res) {\n  req.times = {\n    start: process.hrtime()\n  };\n\n  this.perform('http:request', req, res, function (next) {\n    req.times.middle = process.hrtime();\n    req.times.begin  = process.hrtime(req.times.start);\n    next();\n  }, function (err) {\n    if (err) {\n      //\n      // Do some error handling.\n      //\n    }\n\n    req.times.total = process.hrtime(req.times.start);\n    req.times.after = process.hrtime(req.times.middle);\n    console.log([\n      'Total time: %s',\n      '  Before hooks: %s',\n      '  After  hooks: %s'\n    ].join('\\n'), format(req.times.total), format(req.times.begin), format(req.times.after));\n\n    res.end();\n  });\n}\n\n//\n// Now we consume a new app with hooks.\n//\nvar http = require('http');\n\nvar app = new App();\napp.before('start', function (options, next) {\n  var server = options.server = http.createServer(function (req, res) {\n    app.handle(req, res);\n  });\n\n  server.listen(options.port, next);\n});\n\napp.after('start', function (options, next) {\n  console.log('App started on %s', options.port);\n});\n\napp.before('http:request', function (req, res, next) {\n  //\n  // Do something asynchronous.\n  //\n  next();\n});\n\napp.start({ port: 8080 }, function () {\n  console.log('ok');\n});\n\n//\n// Format process.hrtime()\n//\nfunction format(s) {\n  return (s[0] * 1e3 + s[1] / 1e6) / 1e3;\n}\n```\n\n## More Examples\n\nSee [the example directory](/example)\n\n### Error handling when **no callback is provided**\n\nEach `before` and `after` hook can provide an optional error to short-circuit evaluation of the flow that would normally follow it. This error will be provided to your `callback`, when supplied. In the event that you DO NOT provide a `callback` and a `before`, `after` or `work` function responds with an `Error` _IT WILL BE IGNORED AND FLOW WILL CONTINUE._ e.g.\n\n``` js\nvar Understudy = require('understudy');\nvar actor = new Understudy();\n\nactor.before('always', function (next) {\n  next(new Error('I always fail'));\n});\n\nactor.after('always', function (next) {\n  console.log('I always get called. NO MATTER WHAT');\n  console.log('BUT, only when no callback is supplied.');\n  next(new Error('Another swallowed error'));\n});\n\nactor.perform('always', function (done) {\n  done(new Error('Errors are ignored here too.'));\n});\n```\n\nIn other words (as in the above example): if you do not supply a callback to your `.perform` then `understudy` will consider all of your `before`, `after` and `work` functions as **\"fire and forget\".**\n\n##### LICENSE: MIT\n##### Author: [Bradley Meck](https://github.com/bmeck)\n##### Contributors: [Jarrett Cruger](https://github.com/jcrugzz), [Charlie Robbins](https://github.com/indexzero)\n","publish_time":1443142410755,"_cnpm_publish_time":1443142410755,"dist-tags":{"latest":"4.1.0"}}