-
-
Notifications
You must be signed in to change notification settings - Fork 443
/
dedup.ts
42 lines (34 loc) · 1.14 KB
/
dedup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { filter, pipe, tap } from 'wonka';
import { Exchange, Operation, OperationResult } from '../types';
/** A default exchange for debouncing GraphQL requests. */
export const dedupExchange: Exchange = ({ forward, client }) => {
const dispatchEvent = client.debugTarget!.dispatchEvent;
const inFlightKeys = new Set<number>();
const filterIncomingOperation = (operation: Operation) => {
const { key, operationName } = operation;
if (operationName === 'teardown') {
inFlightKeys.delete(key);
return true;
}
if (operationName !== 'query' && operationName !== 'subscription') {
return true;
}
const isInFlight = inFlightKeys.has(key);
inFlightKeys.add(key);
if (isInFlight) {
dispatchEvent({
type: 'dedup',
message: 'An operation has been deduped.',
operation,
});
}
return !isInFlight;
};
const afterOperationResult = ({ operation }: OperationResult) => {
inFlightKeys.delete(operation.key);
};
return ops$ => {
const forward$ = pipe(ops$, filter(filterIncomingOperation));
return pipe(forward(forward$), tap(afterOperationResult));
};
};