@@ -92,20 +92,25 @@ interface BatchItem<T, A> {
92
92
* Batch remote calls.
93
93
*/
94
94
export abstract class Batch < T , A > {
95
- /**
96
- * Flush after reaching this count.
97
- */
98
- private maxCount = 100 ;
99
-
100
- /**
101
- * Flush after not receiving more requests for this amount of time.
102
- */
103
- private maxTime = 100 ;
104
-
105
- private flushTimeout : number | NodeJS . Timer | undefined ;
106
-
95
+ private idleTimeout : number | NodeJS . Timer | undefined ;
96
+ private maxTimeout : number | NodeJS . Timer | undefined ;
107
97
private batch = < BatchItem < T , A > [ ] > [ ] ;
108
98
99
+ public constructor (
100
+ /**
101
+ * Flush after reaching this amount of time.
102
+ */
103
+ private readonly maxTime = 1000 ,
104
+ /**
105
+ * Flush after reaching this count.
106
+ */
107
+ private readonly maxCount = 100 ,
108
+ /**
109
+ * Flush after not receiving more requests for this amount of time.
110
+ */
111
+ private readonly idleTime = 100 ,
112
+ ) { }
113
+
109
114
public add = ( args : A ) : Promise < T > => {
110
115
return new Promise ( ( resolve , reject ) => {
111
116
this . batch . push ( {
@@ -116,26 +121,29 @@ export abstract class Batch<T, A> {
116
121
if ( this . batch . length >= this . maxCount ) {
117
122
this . flush ( ) ;
118
123
} else {
119
- clearTimeout ( this . flushTimeout as any ) ;
120
- this . flushTimeout = setTimeout ( this . flush , this . maxTime ) ;
124
+ clearTimeout ( this . idleTimeout as any ) ;
125
+ this . idleTimeout = setTimeout ( this . flush , this . idleTime ) ;
126
+ if ( typeof this . maxTimeout === "undefined" ) {
127
+ this . maxTimeout = setTimeout ( this . flush , this . maxTime ) ;
128
+ }
121
129
}
122
130
} ) ;
123
131
}
124
132
125
133
protected abstract remoteCall ( batch : A [ ] ) : Promise < ( T | Error ) [ ] > ;
126
134
127
135
private flush = ( ) : void => {
128
- clearTimeout ( this . flushTimeout as any ) ;
136
+ clearTimeout ( this . idleTimeout as any ) ;
137
+ clearTimeout ( this . maxTimeout as any ) ;
138
+ this . maxTimeout = undefined ;
129
139
130
140
const batch = this . batch ;
131
141
this . batch = [ ] ;
132
142
133
143
this . remoteCall ( batch . map ( ( q ) => q . args ) ) . then ( ( results ) => {
134
144
batch . forEach ( ( item , i ) => {
135
145
const result = results [ i ] ;
136
- if ( ! result ) {
137
- item . reject ( new Error ( "no response" ) ) ;
138
- } else if ( result instanceof Error ) {
146
+ if ( result && result instanceof Error ) {
139
147
item . reject ( result ) ;
140
148
} else {
141
149
item . resolve ( result ) ;
0 commit comments