-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
httpBatchStreamLink.ts
65 lines (60 loc) · 2.13 KB
/
httpBatchStreamLink.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
65
import type { AnyRootTypes } from '@trpc/server/unstable-core-do-not-import';
import type { NonEmptyArray } from '../internals/types';
import type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';
import type { RequesterFn } from './internals/createHTTPBatchLink';
import { createHTTPBatchLink } from './internals/createHTTPBatchLink';
import { getTextDecoder } from './internals/getTextDecoder';
import { streamingJsonHttpRequester } from './internals/parseJSONStream';
import type { TextDecoderEsque } from './internals/streamingUtils';
import type { Operation } from './types';
export type HTTPBatchStreamLinkOptions<TRoot extends AnyRootTypes> =
HTTPBatchLinkOptions<TRoot> & {
/**
* Will default to the webAPI `TextDecoder`,
* but you can use this option if your client
* runtime doesn't provide it.
*/
textDecoder?: TextDecoderEsque;
};
const streamRequester: RequesterFn<HTTPBatchStreamLinkOptions<AnyRootTypes>> = (
requesterOpts,
) => {
const textDecoder = getTextDecoder(requesterOpts.opts.textDecoder);
return (batchOps, unitResolver) => {
const path = batchOps.map((op) => op.path).join(',');
const inputs = batchOps.map((op) => op.input);
const { cancel, promise } = streamingJsonHttpRequester(
{
...requesterOpts,
textDecoder,
path,
inputs,
headers() {
if (!requesterOpts.opts.headers) {
return {};
}
if (typeof requesterOpts.opts.headers === 'function') {
return requesterOpts.opts.headers({
opList: batchOps as NonEmptyArray<Operation>,
});
}
return requesterOpts.opts.headers;
},
},
(index, res) => {
unitResolver(index, res);
},
);
return {
/**
* return an empty array because the batchLoader expects an array of results
* but we've already called the `unitResolver` for each of them, there's
* nothing left to do here.
*/
promise: promise.then(() => []),
cancel,
};
};
};
export const unstable_httpBatchStreamLink =
createHTTPBatchLink(streamRequester);