@loglayer/context-manager-linked
Version:
Context manager for loglayer that keeps context between parent and all children.
74 lines (73 loc) • 2.5 kB
JavaScript
//#region src/LinkedContextManager.ts
/**
* A context manager that keeps context data synchronized between parent and all children (bi-directional).
*/
var LinkedContextManager = class LinkedContextManager {
contextContainer = {
data: {},
hasContext: false
};
/**
* Sets the context data to be included with every log entry. Set to `undefined` to clear the context data.
*/
setContext(context) {
if (!context) {
for (const key in this.contextContainer.data) if (Object.hasOwn(this.contextContainer.data, key)) delete this.contextContainer.data[key];
this.contextContainer.hasContext = false;
return;
}
Object.assign(this.contextContainer.data, context);
this.contextContainer.hasContext = true;
}
/**
* Appends context data to the existing context data.
*/
appendContext(context) {
Object.assign(this.contextContainer.data, context);
this.contextContainer.hasContext = true;
}
/**
* Returns the context data to be included with every log entry.
*/
getContext() {
return this.contextContainer.data;
}
/**
* Returns true if context data is present.
*/
hasContextData() {
return this.contextContainer.hasContext;
}
/**
* Clears the context data. If keys are provided, only those keys will be removed.
* If no keys are provided, all context data will be cleared.
*/
clearContext(keys) {
if (keys === void 0) {
for (const key in this.contextContainer.data) if (Object.hasOwn(this.contextContainer.data, key)) delete this.contextContainer.data[key];
this.contextContainer.hasContext = false;
return;
}
const keysToRemove = Array.isArray(keys) ? keys : [keys];
for (const key of keysToRemove) delete this.contextContainer.data[key];
this.contextContainer.hasContext = Object.keys(this.contextContainer.data).length > 0;
}
/**
* Links the child context manager's context to be the same as the parent context manager's context.
*/
onChildLoggerCreated({ parentContextManager, childContextManager }) {
if (childContextManager instanceof LinkedContextManager) childContextManager.contextContainer = this.contextContainer;
else childContextManager.setContext(this.getContext());
}
/**
* Creates a new instance of the context manager that shares the same context data.
* The clone maintains a bi-directional link with the original context manager.
*/
clone() {
const clone = new LinkedContextManager();
clone.contextContainer = this.contextContainer;
return clone;
}
};
//#endregion
export { LinkedContextManager };