2022 update
NodeJS is proposing a new built-in for doing exactly that: Asynchronous context tracking.
Thanks to @Emmanuel Meric de Bellefon for pointing this out.
Defining the desired behavior
If you only need it for synchronous code, you could do something relatively simple. All you need is to specify where the boundaries are.
In React, you do this with JSX
<Context.Provider value={2}>
<MyComponent />
</Context.Provider>
In this example, the value of Context
will be 2
for MyComponent
but outside of the bounds of <Context.Provider>
it will be whatever the value was before that.
If I were to translate that in vanilla JS, I would probably want it to look something like this:
const myFunctionWithContext = context.provider(2, myFunction)
myFunctionWithContext('an argument')
In this example, I would expect the value of context
to be 2
within myFunction
but outside of the bounds of context.provider()
it would be whatever value was set before.
How to work the problem
At its most basic, this could be solved by a global object
// we define a "context"
globalThis.context = 'initial value'
function a() {
// we can access the context
const currentValue = globalThis.context
console.log(`context value in a: ${currentValue}`)
// we can modify the context for the "children"
globalThis.context = 'value from a'
b()
// we undo the modification to restore the context
globalThis.context = currentValue
}
function b() {
console.log(`context value in b: ${globalThis.context}`)
}
a()
Now we know that it's never wise to pollute the global scope globalThis
or window
. So we could use a Symbol instead, to make sure there can't be any naming conflict:
const context = Symbol()
globalThis[context] = 'initial value'
function a() {
console.log(`context value in a: ${globalThis[context]}`)
}
a()
However, even though this solution will never cause a conflict with the global scope, it's still not ideal, and doesn't scale well for multiple contexts. So let's make a "context factory" module:
// in createContext.js
const contextMap = new Map() // all of the declared contexts, one per `createContext` call
/* export default */ function createContext(value) {
const key = Symbol('context') // even though we name them the same, Symbols can never conflict
contextMap.set(key, value)
function provider(value, callback) {
const old = contextMap.get(key)
contextMap.set(key, value)
callback()
contextMap.set(key, old)
}
function consumer() {
return contextMap.get(key)
}
return {
provider,
consumer,
}
}
// in index.js
const contextOne = createContext('initial value')
const contextTwo = createContext('other context') // we can create multiple contexts without conflicts
function a() {
console.log(`value in a: ${contextOne.consumer()}`)
contextOne.provider('value from a', b)
console.log(`value in a: ${contextOne.consumer()}`)
}
function b() {
console.log(`value in b: ${contextOne.consumer()}`)
console.log(`value in b: ${contextTwo.consumer()}`)
}
a()
Now, as long as you're only using this for synchronous code, this works by simply overriding a value before a callback and reseting it after (in provider
).
Solution for synchronous code
If you want to structure your code like you would in react, here's what it would look like with a few separate modules:
// in createContext.js
const contextMap = new Map()
/* export default */ function createContext(value) {
const key = Symbol('context')
contextMap.set(key, value)
return {
provider(value, callback) {
const old = contextMap.get(key)
contextMap.set(key, value)
callback()
contextMap.set(key, old)
},
consumer() {
return contextMap.get(key)
}
}
}
// in myContext.js
/* import createContext from './createContext.js' */
const myContext = createContext('initial value')
/* export */ const provider = myContext.provider
/* export */ const consumer = myContext.consumer
// in a.js
/* import { provider, consumer } from './myContext.js' */
/* import b from './b.js' */
/* export default */ function a() {
console.log(`value in a: ${consumer()}`)
provider('value from a', b)
console.log(`value in a: ${consumer()}`)
}
// in b.js
/* import { consumer } from './myContext.js' */
/* export default */ function b() {
console.log(`value in b: ${consumer()}`)
}
// in index.js
/* import a from './a.js' */
a()
Going further: the problem of asynchronous code
The solution proposed above would not work if b()
was an async function, because as soon as b
returns, the context value is reset to its value in a()
(that's how provider
works). For example:
const contextMap = new Map()
function createContext(value) {
const key = Symbol('context')
contextMap.set(key, value)
function provider(value, callback) {
const old = contextMap.get(key)
contextMap.set(key, value)
callback()
contextMap.set(key, old)
}
function consumer() {
return contextMap.get(key)
}
return {
provider,
consumer
}
}
const { provider, consumer } = createContext('initial value')
function a() {
console.log(`value in a: ${consumer()}`)
provider('value from a', b)
console.log(`value in a: ${consumer()}`)
}
async function b() {
await new Promise(resolve => setTimeout(resolve, 1000))
console.log(`value in b: ${consumer()}`) // we want this to log 'value from a', but it logs 'initial value'
}
a()
So far, I don't really see how to manage the issue of async functions properly, but I bet it could be done with the use of Symbol
, this
and Proxy
.
Using this
to pass context
While developing a solution for synchronous code, we've seen that we can "afford" to add properties to an object that "isn't ours" as long as we're using Symbol
keys to do so (like we did on globalThis
in the first example). We also know that functions are always called with an implicit this
argument that is either
- the global scope (
globalThis
),
- the parent scope (when calling
obj.func()
, within func
, this
will be obj
)
- an arbitrary scope object (when using
.bind
, .call
or .apply
)
- in some cases, an arbitrary primitive value (only possible in strict mode)
In addition, javascript lets us define a Proxy to be the interface between an object and whatever script uses that object. Within a Proxy
we can define a set of traps that will each handle a specific way in which our object is used. The one that is interesting for our issue is apply which traps function calls and gives us access to the this
that the function will be called with.
Knowing this, we can "augment" the this
of our function called with a context provider context.provider(value, myFunction)
with a Symbol referring to our context:
{
apply: (target, thisArg = {}, argumentsList) => {
const scope = Object.assign({}, thisArg, {[id]: key}) // augment `this`
return Reflect.apply(target, scope, argumentsList) // call function
}
}
Reflect
will call the function target
with this
set to scope
and the arguments from argumentsList
As long as what we "store" in this
allows us to get the "current" value of the scope (the value where context.provider()
was called) then we should be able to access this value from within myFunction
and we don't need to set/reset a unique object like we did for the synchronous solution.
First async solution: shallow context
Putting it all together, here's an initial attempt at a asynchronous solution for a react-like context. However, unlike with the prototype chain, this
is not inherited automatically when a function is called from within another function. Because of this the context in the following solution only survives 1 level of function calls:
function createContext(initial) {
const id = Symbol()
function provider(value, callback) {
return new Proxy(callback, {
apply: (target, thisArg, argumentsList) => {
const scope = Object.assign({}, thisArg, {[id]: value})
return Reflect.apply(target, scope, argumentsList)
}
})
}
function consumer(scope = {}) {
return id in scope ? scope[id] : initial
}
return {
provider,
consumer,
}
}
const myContext = createContext('initial value')
function a() {
console.log(`value in a: ${myContext.consumer(this)}`)
const bWithContext = myContext.provider('value from a', b)
bWithContext()
const cWithContext = myContext.provider('value from a', c)
cWithContext()
console.log(`value in a: ${myContext.consumer(this)}`)
}
function b() {
console.log(`value in b: ${myContext.consumer(this)}`)
}
async function c() {
await new Promise(resolve => setTimeout(resolve, 200))
console.log(`value in c: ${myContext.consumer(this)}`) // works in async!
b() // logs 'initial value', should log 'value from a' (the same as "value in c")
}
a()
Second asynchronous solution: context forwarding
A potential solution for the context to survive a function call within another function call could be to have to explicitly forward the context to any function call (which could quickly become cumbersome). From the example above, c()
would change to:
async function c() {
await new Promise(resolve => setTimeout(resolve, 200))
console.log(`value in c: ${myContext.consumer(this)}`)
const bWithContext = myContext.forward(this, b)
bWithContext() // logs 'value from a'
}
where myContext.forward
is just a consumer
to get the value and directly afterwards a provider
to pass it along:
function forward(scope, callback) {
const value = consumer(scope)
return provider(value, callback)
}
Adding this to our previous solution:
function createContext(initial) {
const id = Symbol()
function provider(value, callback) {
return new Proxy(callback, {
apply: (target, thisArg, argumentsList) => {
const scope = Object.assign({}, thisArg, {[id]: value})
return Reflect.apply(target, scope, argumentsList)
}
})
}
function consumer(scope = {}) {
return id in scope ? scope[id] : initial
}
function forward(scope, callback) {
const value = consumer(scope)
return provider(value, callback)
}
return {
provider,
consumer,
forward,
}
}
const myContext = createContext('initial value')
function a() {
console.log(`value in a: ${myContext.consumer(this)}`)
const bWithContext = myContext.provider('value from a', b)
bWithContext()
const cWithContext = myContext.provider('value from a', c)
cWithContext()
console.log(`value in a: ${myContext.consumer(this)}`)
}
function b() {
console.log(`value in b: ${myContext.consumer(this)}`)
}
async function c() {
await new Promise(resolve => setTimeout(resolve, 200))
console.log(`value in c: ${myContext.consumer(this)}`)
const bWithContext = myContext.forward(this, b)
bWithContext()
}
a()
Context on async functions without explicit forwarding
Now I'm stuck... I'm open to ideas!
typeorm
and I need to keep both connections names as "default" but it does not work since the two servers seem to share the same instance oftypeorm
. My thought is that having something like React Context in Nodejs could enclose each server with its own instance oftypeorm
. Apart from that, I think this pattern could apply to any case where we need a "context" in nodejs. – Daddy