@twin.org/context
Version:
Helper methods/classes for context handling
49 lines • 1.52 kB
JavaScript
import { BaseError, GeneralError } from "@twin.org/core";
/**
* Class to maintain context ids and execute an async method.
*/
export class ContextIdStore {
/**
* Runtime name for the class.
*/
static CLASS_NAME = "ContextIdStore";
/**
* The async local storage for the context ids.
*/
static _storage;
/**
* Execute the method wrapped in the context.
* @param contextIds The context IDs.
* @param asyncMethod The async method to run.
* @returns Nothing.
*/
static async run(contextIds, asyncMethod) {
return (await ContextIdStore.createStorage()).run(contextIds, asyncMethod);
}
/**
* Get the context IDs.
* @returns The context IDs.
*/
static async getContextIds() {
return (await ContextIdStore.createStorage()).getStore();
}
/**
* Create the storage if it doesn't exist.
* @returns The storage.
*/
static async createStorage() {
if (!ContextIdStore._storage) {
try {
const hooks = await import("node:async_hooks");
ContextIdStore._storage = new hooks.AsyncLocalStorage({
name: "AsyncContextIdsStorage"
});
}
catch (err) {
throw new GeneralError(ContextIdStore.CLASS_NAME, "asyncHooksNotAvailable", undefined, BaseError.fromError(err));
}
}
return ContextIdStore._storage;
}
}
//# sourceMappingURL=contextIdStore.js.map