Skip to content

Commit

Permalink
fix: separate timer for each key
Browse files Browse the repository at this point in the history
  • Loading branch information
zlrlo committed Jan 9, 2023
1 parent 1d5be2b commit f583cc8
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 4 deletions.
65 changes: 65 additions & 0 deletions src/link/batch/__tests__/batchLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,71 @@ describe('OperationBatcher', () => {
}
});

itAsync('should be able to consume from a queue containing multiple queries with different batch keys', (resolve, reject) => {
const request2: Operation = createOperation(
{},
{
query,
},
);

const BH = createMockBatchHandler(
{
request: { query },
result: { data },
},
{
request: { query },
result: { data },
},
);

let key = true;
const batchKey = () => {
key = !key;
return '' + !key;
};

const myBatcher = new OperationBatcher({
batchInterval: 10,
batchMax: 10,
batchHandler: BH,
batchKey
});

const observable1 = myBatcher.enqueueRequest({ operation });
const observable2 = myBatcher.enqueueRequest({ operation: request2 });

let notify = false;
observable1.subscribe(resultObj1 => {
try {
expect(resultObj1).toEqual({ data });
} catch (e) {
reject(e);
}

if (notify) {
resolve();
} else {
notify = true;
}
});

observable2.subscribe(resultObj2 => {
try {
expect(resultObj2).toEqual({ data });
} catch (e) {
reject(e);
}

if (notify) {
resolve();
} else {
notify = true;
}
});
});

itAsync('should return a promise when we enqueue a request and resolve it with a result', (resolve, reject) => {
const BH = createMockBatchHandler({
request: { query },
Expand Down
8 changes: 4 additions & 4 deletions src/link/batch/batching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class OperationBatcher {
// Queue on which the QueryBatcher will operate on a per-tick basis.
private batchesByKey = new Map<string, RequestBatch>();

private scheduledBatchTimer: ReturnType<typeof setTimeout>;
private scheduledBatchTimerByKey = new Map<string, ReturnType<typeof setTimeout>>();
private batchDebounce?: boolean;
private batchInterval?: number;
private batchMax: number;
Expand Down Expand Up @@ -211,9 +211,9 @@ export class OperationBatcher {
}

private scheduleQueueConsumption(key: string): void {
clearTimeout(this.scheduledBatchTimer);
this.scheduledBatchTimer = setTimeout(() => {
clearTimeout(this.scheduledBatchTimerByKey.get(key));
this.scheduledBatchTimerByKey.set(key, setTimeout(() => {
this.consumeQueue(key);
}, this.batchInterval);
}, this.batchInterval));
}
}

0 comments on commit f583cc8

Please sign in to comment.