File tree Expand file tree Collapse file tree 1 file changed +46
-3
lines changed Expand file tree Collapse file tree 1 file changed +46
-3
lines changed Original file line number Diff line number Diff line change 10
10
*/
11
11
export class Context {
12
12
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
+ }
14
29
15
30
do < T > ( func : ( ) => T ) : T {
16
31
const prevContext = _context ;
@@ -21,15 +36,43 @@ export class Context {
21
36
_context = prevContext ;
22
37
}
23
38
}
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
+ }
24
56
}
25
57
26
58
/**
27
- * Default context has "context.value === undefined".
59
+ * Default context has "context.id === undefined".
28
60
*/
29
61
let _context : any = new Context ( ) ;
30
62
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
+
31
74
/**
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 .
33
76
*
34
77
* const context = getContext();
35
78
*/
You can’t perform that action at this time.
0 commit comments