Skip to content

Instantly share code, notes, and snippets.

@tlivings
Created February 1, 2017 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlivings/d5391512e81078d87a7c63467cbfd4c5 to your computer and use it in GitHub Desktop.
Save tlivings/d5391512e81078d87a7c63467cbfd4c5 to your computer and use it in GitHub Desktop.
Stateful domain thing for maintaining context across async calls
'use strict';
const Domain = require('domain');
const create = function (initialState = {}) {
const domain = Domain.create();
domain.state = initialState;
const enter = domain.enter;
const exit = domain.exit;
domain.enter = function () {
const state = process.domain ? process.domain.state : undefined;
if (process.domain) {
domain.parent = process.domain;
domain.state = Object.assign(domain.state, process.domain.state);
}
enter.call(domain);
};
domain.exit = function () {
const state = domain.state;
if (domain.parent) {
domain.parent = undefined;
}
exit.call(domain);
if (process.domain) {
process.domain.state = Object.assign(process.domain.state || {}, state);
}
}
return domain;
};
module.exports = { create, get state() { return process.domain && process.domain.state } };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment