Skip to content

Commit

Permalink
chore: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexey Zorkaltsev committed Oct 16, 2023
1 parent e785f2a commit 5f14cb0
Showing 1 changed file with 46 additions and 3 deletions.
49 changes: 46 additions & 3 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(func: () => T): T {
const prevContext = _context;
Expand All @@ -21,15 +36,43 @@ export class Context {
_context = prevContext;
}
}

findContextByClass<T extends Context>(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();
*/
Expand Down

0 comments on commit 5f14cb0

Please sign in to comment.