node-context
Advanced tools
+31
-6
@@ -14,4 +14,13 @@ /** | ||
| var utils = require('./utils'); | ||
| /** | ||
| * Constants | ||
| */ | ||
| var COPY_EXCLUDE = { | ||
| canceled: true, | ||
| deadline: true, | ||
| domain: true, | ||
| finished: true, | ||
| }; | ||
| /** | ||
@@ -43,6 +52,6 @@ * Context instance. | ||
| if (parent) { | ||
| parent.once('cancel', function() { self.cancel(); }); | ||
| parent.once('cancel', function(reason) { self.cancel(reason); }); | ||
| parent.once('finish', function() { self.end(); }); | ||
| utils.copyEvent(parent, this); | ||
| parent.values(this); | ||
@@ -76,7 +85,7 @@ // reduce deadline to parent's or schedule our own shorter deadline | ||
| Context.prototype.cancel = function() { | ||
| Context.prototype.cancel = function(reason) { | ||
| if (this.canceled || this.finished) return false; | ||
| this.canceled = true; | ||
| this.emit('cancel'); | ||
| this.emit('cancel', reason); | ||
@@ -110,2 +119,18 @@ return this.end(); | ||
| /** | ||
| * Return or merges values | ||
| */ | ||
| Context.prototype.values = function(obj) { | ||
| obj = obj || {}; | ||
| for (var p in this) { | ||
| if (this.hasOwnProperty(p) && p[0] !== '_' && !COPY_EXCLUDE[p]) { | ||
| obj[p] = this[p]; | ||
| } | ||
| } | ||
| return obj; | ||
| }; | ||
| /** | ||
| * Schedule timeout | ||
@@ -117,3 +142,3 @@ */ | ||
| var timeout = function() { self.cancel(); }; | ||
| var timeout = function() { self.cancel('timeout'); }; | ||
@@ -120,0 +145,0 @@ if (self.deadline > now) { |
+2
-2
| { | ||
| "name": "node-context", | ||
| "version": "0.4.0", | ||
| "version": "0.6.0", | ||
| "description": "Context type that carries deadlines, cancelation signals, and other request-scoped values.", | ||
@@ -11,3 +11,3 @@ "main": "lib", | ||
| "mocha": "^2.1.0", | ||
| "should": "^5.0.1", | ||
| "should": "^7.0.2", | ||
| "sinon": "^1.12.2" | ||
@@ -14,0 +14,0 @@ }, |
+7
-0
@@ -74,2 +74,9 @@ # Context [](https://travis-ci.org/silas/node-context) | ||
| <a name="context-values"/> | ||
| ### ctx.values([object]) | ||
| Return context values. | ||
| If `object` is provided then the context values will be merged into it. | ||
| ## Example | ||
@@ -76,0 +83,0 @@ |
-31
| /** | ||
| * Utils. | ||
| */ | ||
| 'use strict'; | ||
| /** | ||
| * Copy properties from one EventListener to another. | ||
| */ | ||
| var COPY_EVENT_EXCLUDE = { | ||
| canceled: true, | ||
| deadline: true, | ||
| domain: true, | ||
| finished: true, | ||
| }; | ||
| function copyEvent(src, dst) { | ||
| for (var p in src) { | ||
| if (src.hasOwnProperty(p) && p[0] !== '_' && !COPY_EVENT_EXCLUDE[p]) { | ||
| dst[p] = src[p]; | ||
| } | ||
| } | ||
| return dst; | ||
| } | ||
| /** | ||
| * Module exports. | ||
| */ | ||
| exports.copyEvent = copyEvent; |
7632
0.91%126
5.88%6
-14.29%123
-3.91%