Created
February 1, 2017 22:31
-
-
Save tlivings/d5391512e81078d87a7c63467cbfd4c5 to your computer and use it in GitHub Desktop.
Stateful domain thing for maintaining context across async calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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