From 5f14cb050865ec665e26a025cec8e16ac2ce19ad Mon Sep 17 00:00:00 2001 From: Alexey Zorkaltsev Date: Tue, 17 Oct 2023 02:01:25 +0300 Subject: [PATCH] chore: wip --- src/context.ts | 49 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/context.ts b/src/context.ts index 74a6ff45..a11d0402 100644 --- a/src/context.ts +++ b/src/context.ts @@ -10,7 +10,22 @@ */ export class Context { - constructor(readonly value?: any) { } + readonly id?: any; + readonly parent?: Context; + + constructor(parent?: Context) { + if (parent) { + if (parent.id) { + this.id = parent.id; + } + this.parent = parent; + } else { + const id = newId(); + if (id) { + this.id = id; + } + } + } do(func: () => T): T { const prevContext = _context; @@ -21,15 +36,43 @@ export class Context { _context = prevContext; } } + + findContextByClass(type: Function): T | null { + let ctx: Context | undefined = this; + + while (ctx) { + if (ctx instanceof type) { + return ctx as T; + } + ctx = ctx.parent; + } + + return null; + } + + toString() { + return this.id ? `${this.id}: ` : ''; + } } /** - * Default context has "context.value === undefined". + * Default context has "context.id === undefined". */ let _context: any = new Context(); +let newId: () => any = () => undefined; + +/** + * Set the id generator for a new context. By default, the id remain undefined. + * + * @param generateNewId + */ +export function setContextNewId(generateNewId: () => any) { + newId = generateNewId; +} + /** - * The context must be taken before a first await, it is more reliable to take it in the first line of the function. + * The context must be taken in the beging function before a first await. * * const context = getContext(); */