Skip to content

Commit 5f14cb0

Browse files
author
Alexey Zorkaltsev
committed
chore: wip
1 parent e785f2a commit 5f14cb0

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

src/context.ts

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,22 @@
1010
*/
1111
export class Context {
1212

13-
constructor(readonly value?: any) { }
13+
readonly id?: any;
14+
readonly parent?: Context;
15+
16+
constructor(parent?: Context) {
17+
if (parent) {
18+
if (parent.id) {
19+
this.id = parent.id;
20+
}
21+
this.parent = parent;
22+
} else {
23+
const id = newId();
24+
if (id) {
25+
this.id = id;
26+
}
27+
}
28+
}
1429

1530
do<T>(func: () => T): T {
1631
const prevContext = _context;
@@ -21,15 +36,43 @@ export class Context {
2136
_context = prevContext;
2237
}
2338
}
39+
40+
findContextByClass<T extends Context>(type: Function): T | null {
41+
let ctx: Context | undefined = this;
42+
43+
while (ctx) {
44+
if (ctx instanceof type) {
45+
return ctx as T;
46+
}
47+
ctx = ctx.parent;
48+
}
49+
50+
return null;
51+
}
52+
53+
toString() {
54+
return this.id ? `${this.id}: ` : '';
55+
}
2456
}
2557

2658
/**
27-
* Default context has "context.value === undefined".
59+
* Default context has "context.id === undefined".
2860
*/
2961
let _context: any = new Context();
3062

63+
let newId: () => any = () => undefined;
64+
65+
/**
66+
* Set the id generator for a new context. By default, the id remain undefined.
67+
*
68+
* @param generateNewId
69+
*/
70+
export function setContextNewId(generateNewId: () => any) {
71+
newId = generateNewId;
72+
}
73+
3174
/**
32-
* The context must be taken before a first await, it is more reliable to take it in the first line of the function.
75+
* The context must be taken in the beging function before a first await.
3376
*
3477
* const context = getContext();
3578
*/

0 commit comments

Comments
 (0)