@javarome/context
v1.0.0
Published
Context-management library
Downloads
3
Readme
context
Allows to manage scoped data.
Usage
const someContext = new Context("some context name")
Read/write values
someContext.set("someKey", "someValue")
someContext.set("other key", new OtherValue())
const someValue = someContext.get("someKey")
Nesting
const subContext = someContext.enter("sub context")
try {
subContext.set("sub value", new OtherValue())
const someValue = someContext.get("someKey") // Still get data from parent context
subContext.set("someKey", "someSubValue") // Now overrides parent value
} finally {
subContext.leave()
}
Nested execution
A convenience method to automatically create a nested context and leaving it once executed.
const wasntDone = someContext.exec(nestedContext => (nestedContext, otherParam) => {
const wasDone = nestedContext.get("nestedDone")
nestedContext.set("nestedDone", true)
return !wasDone
})
same for async functions:
const wasntDone = await someContext.execAsync(nestedContext => async(nestedContext, otherParam) => {
const wasDone = nestedContext.get("nestedDone")
await something()
nestedContext.set("nestedDone", true)
return !wasDone
})
Logging
A LoggedContext
is a Context
with a built-in Logger
.
It overrides the enter()
, exec()
, execAsync()
APIs to set logging prefixes describing the current/nested context.
For instance:
const someContext = new LoggedContext("some context")
someContext.logger.log("running") // Prints "some context: running"
const subContext = someContext.enter("sub context")
try {
subContext.logger.log("running") // Prints "some context-sub context: running"
} finally {
someContext.logger.log("stopping") // Prints "some context: stopping"
subContext.leave()
}