This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-agent.entry.ts
64 lines (55 loc) · 1.83 KB
/
fetch-agent.entry.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { cxDynamic, CxEntry } from '@proc7ts/context-values';
import { EventSender, OnEvent, onSupplied } from '@proc7ts/fun-events';
export type FetchAgent<TResponse extends unknown[]> = (
this: void,
next: (this: void, request?: Request) => OnEvent<TResponse>,
request: Request,
) => EventSender<TResponse>;
export type CombinedFetchAgent<TResponse extends unknown[]> = (
this: void,
next: (this: void, request: Request) => OnEvent<TResponse>,
request: Request,
) => OnEvent<TResponse>;
export function cxFetchAgent<TResponse extends unknown[]>(): CxEntry.Definer<
CombinedFetchAgent<TResponse>,
FetchAgent<TResponse>
> {
return cxDynamic<
CombinedFetchAgent<TResponse>,
FetchAgent<TResponse>,
CombinedFetchAgent<TResponse>
>({
create: FetchAgent$combine,
byDefault: _ => FetchAgent$default,
assign: ({ get, to }) => {
const agent: CombinedFetchAgent<TResponse> = (next, request) => get()(next, request);
return receiver => to((_, by) => receiver(agent, by));
},
});
}
function FetchAgent$default<TResponse extends any[]>(
next: (this: void, request: Request) => OnEvent<TResponse>,
request: Request,
): OnEvent<TResponse> {
return next(request);
}
function FetchAgent$combine<TResponse extends any[]>(
agents: FetchAgent<TResponse>[],
_target: CxEntry.Target<CombinedFetchAgent<TResponse>, FetchAgent<TResponse>>,
): CombinedFetchAgent<TResponse> {
return (next, request) => {
const fetch: (agentIdx: number, agentRequest: Request) => OnEvent<TResponse> = (
agentIdx,
agentRequest,
) => {
const agent = agents[agentIdx];
if (!agent) {
return next(agentRequest);
}
return onSupplied(
agent((nextRequest = agentRequest) => fetch(agentIdx + 1, nextRequest), agentRequest),
);
};
return fetch(0, request);
};
}