@trpc/client 10.0.0-alpha.2 → 10.0.0-alpha.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/dist/{declarations/src/TRPCClientError.d.ts → TRPCClientError.d.ts} +21 -29
  2. package/dist/TRPCClientError.d.ts.map +1 -0
  3. package/dist/{declarations/src/createTRPCClient.d.ts → createTRPCClient.d.ts} +5 -5
  4. package/dist/createTRPCClient.d.ts.map +1 -0
  5. package/dist/{declarations/src/getFetch.d.ts → getFetch.d.ts} +1 -1
  6. package/dist/getFetch.d.ts.map +1 -0
  7. package/dist/{declarations/src/index.d.ts → index.d.ts} +4 -4
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +1417 -0
  10. package/dist/index.mjs +1391 -0
  11. package/dist/index.ts.js +1 -0
  12. package/dist/{declarations/src/internals → internals}/TRPCClient.d.ts +61 -64
  13. package/dist/internals/TRPCClient.d.ts.map +1 -0
  14. package/dist/{declarations/src/internals → internals}/dataLoader.d.ts +17 -14
  15. package/dist/internals/dataLoader.d.ts.map +1 -0
  16. package/dist/{declarations/src/internals → internals}/fetchHelpers.d.ts +2 -2
  17. package/dist/internals/fetchHelpers.d.ts.map +1 -0
  18. package/dist/{declarations/src/internals → internals}/retryDelay.d.ts +1 -1
  19. package/dist/internals/retryDelay.d.ts.map +1 -0
  20. package/dist/links/dedupeLink.d.ts +4 -0
  21. package/dist/links/dedupeLink.d.ts.map +1 -0
  22. package/dist/links/httpBatchLink.d.ts +8 -0
  23. package/dist/links/httpBatchLink.d.ts.map +1 -0
  24. package/dist/{declarations/src/links → links}/httpLink.d.ts +4 -4
  25. package/dist/links/httpLink.d.ts.map +1 -0
  26. package/dist/links/index.d.ts +9 -0
  27. package/dist/links/index.d.ts.map +1 -0
  28. package/dist/{declarations/src/links → links}/internals/createChain.d.ts +7 -7
  29. package/dist/links/internals/createChain.d.ts.map +1 -0
  30. package/dist/links/internals/httpUtils.d.ts +30 -0
  31. package/dist/links/internals/httpUtils.d.ts.map +1 -0
  32. package/dist/links/internals/transformOperationResult.d.ts +30 -0
  33. package/dist/links/internals/transformOperationResult.d.ts.map +1 -0
  34. package/dist/{declarations/src/links → links}/loggerLink.d.ts +38 -38
  35. package/dist/links/loggerLink.d.ts.map +1 -0
  36. package/dist/links/retryLink.d.ts +6 -0
  37. package/dist/links/retryLink.d.ts.map +1 -0
  38. package/dist/{declarations/src/links → links}/splitLink.d.ts +13 -13
  39. package/dist/links/splitLink.d.ts.map +1 -0
  40. package/dist/{declarations/src/links → links}/types.d.ts +42 -39
  41. package/dist/links/types.d.ts.map +1 -0
  42. package/dist/{declarations/src/links → links}/wsLink.d.ts +19 -19
  43. package/dist/links/wsLink.d.ts.map +1 -0
  44. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.cjs.dev.js +68 -38
  45. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.cjs.prod.js +68 -38
  46. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.esm.js +67 -37
  47. package/links/httpLink/dist/trpc-client-links-httpLink.cjs.dev.js +52 -29
  48. package/links/httpLink/dist/trpc-client-links-httpLink.cjs.prod.js +52 -29
  49. package/links/httpLink/dist/trpc-client-links-httpLink.esm.js +52 -29
  50. package/links/loggerLink/dist/trpc-client-links-loggerLink.cjs.dev.js +19 -31
  51. package/links/loggerLink/dist/trpc-client-links-loggerLink.cjs.prod.js +19 -31
  52. package/links/loggerLink/dist/trpc-client-links-loggerLink.esm.js +19 -31
  53. package/links/splitLink/dist/trpc-client-links-splitLink.cjs.dev.js +7 -20
  54. package/links/splitLink/dist/trpc-client-links-splitLink.cjs.prod.js +7 -20
  55. package/links/splitLink/dist/trpc-client-links-splitLink.esm.js +7 -20
  56. package/links/wsLink/dist/trpc-client-links-wsLink.cjs.dev.js +84 -60
  57. package/links/wsLink/dist/trpc-client-links-wsLink.cjs.prod.js +84 -60
  58. package/links/wsLink/dist/trpc-client-links-wsLink.esm.js +84 -60
  59. package/package.json +26 -23
  60. package/src/TRPCClientError.ts +3 -11
  61. package/src/createTRPCClient.ts +1 -1
  62. package/src/index.ts +1 -1
  63. package/src/internals/TRPCClient.ts +52 -36
  64. package/src/internals/dataLoader.ts +120 -45
  65. package/src/links/dedupeLink.test.ts +1 -1
  66. package/src/links/dedupeLink.ts +3 -5
  67. package/src/links/httpBatchLink.ts +64 -31
  68. package/src/links/httpLink.ts +4 -4
  69. package/src/links/index.ts +8 -0
  70. package/src/links/internals/createChain.test.ts +5 -5
  71. package/src/links/internals/createChain.ts +3 -3
  72. package/src/links/internals/httpUtils.ts +116 -0
  73. package/src/links/internals/transformOperationResult.ts +40 -12
  74. package/src/links/loggerLink.ts +1 -2
  75. package/src/links/retryLink.ts +1 -2
  76. package/src/links/splitLink.test.ts +3 -3
  77. package/src/links/splitLink.ts +5 -5
  78. package/src/links/types.ts +13 -8
  79. package/src/links/wsLink.ts +12 -12
  80. package/dist/TRPCClientError-a5312a5f.cjs.dev.js +0 -74
  81. package/dist/TRPCClientError-e1da1ef0.esm.js +0 -72
  82. package/dist/TRPCClientError-ea7d89b2.cjs.prod.js +0 -74
  83. package/dist/createChain-93a38e1c.cjs.dev.js +0 -27
  84. package/dist/createChain-e45e052a.cjs.prod.js +0 -27
  85. package/dist/createChain-e45e6cf2.esm.js +0 -25
  86. package/dist/declarations/src/TRPCClientError.d.ts.map +0 -1
  87. package/dist/declarations/src/createTRPCClient.d.ts.map +0 -1
  88. package/dist/declarations/src/getFetch.d.ts.map +0 -1
  89. package/dist/declarations/src/index.d.ts.map +0 -1
  90. package/dist/declarations/src/internals/TRPCClient.d.ts.map +0 -1
  91. package/dist/declarations/src/internals/dataLoader.d.ts.map +0 -1
  92. package/dist/declarations/src/internals/fetchHelpers.d.ts.map +0 -1
  93. package/dist/declarations/src/internals/retryDelay.d.ts.map +0 -1
  94. package/dist/declarations/src/links/httpBatchLink.d.ts +0 -5
  95. package/dist/declarations/src/links/httpBatchLink.d.ts.map +0 -1
  96. package/dist/declarations/src/links/httpLink.d.ts.map +0 -1
  97. package/dist/declarations/src/links/httpUtils.d.ts +0 -22
  98. package/dist/declarations/src/links/httpUtils.d.ts.map +0 -1
  99. package/dist/declarations/src/links/internals/createChain.d.ts.map +0 -1
  100. package/dist/declarations/src/links/internals/transformOperationResult.d.ts +0 -16
  101. package/dist/declarations/src/links/internals/transformOperationResult.d.ts.map +0 -1
  102. package/dist/declarations/src/links/loggerLink.d.ts.map +0 -1
  103. package/dist/declarations/src/links/splitLink.d.ts.map +0 -1
  104. package/dist/declarations/src/links/transformerLink.d.ts +0 -4
  105. package/dist/declarations/src/links/transformerLink.d.ts.map +0 -1
  106. package/dist/declarations/src/links/types.d.ts.map +0 -1
  107. package/dist/declarations/src/links/wsLink.d.ts.map +0 -1
  108. package/dist/declarations/src/rx/index.d.ts +0 -3
  109. package/dist/declarations/src/rx/index.d.ts.map +0 -1
  110. package/dist/declarations/src/rx/observable.d.ts +0 -4
  111. package/dist/declarations/src/rx/observable.d.ts.map +0 -1
  112. package/dist/declarations/src/rx/operators/index.d.ts +0 -4
  113. package/dist/declarations/src/rx/operators/index.d.ts.map +0 -1
  114. package/dist/declarations/src/rx/operators/map.d.ts +0 -3
  115. package/dist/declarations/src/rx/operators/map.d.ts.map +0 -1
  116. package/dist/declarations/src/rx/operators/share.d.ts +0 -6
  117. package/dist/declarations/src/rx/operators/share.d.ts.map +0 -1
  118. package/dist/declarations/src/rx/operators/tap.d.ts +0 -3
  119. package/dist/declarations/src/rx/operators/tap.d.ts.map +0 -1
  120. package/dist/declarations/src/rx/types.d.ts +0 -29
  121. package/dist/declarations/src/rx/types.d.ts.map +0 -1
  122. package/dist/declarations/src/rx/util/identity.d.ts +0 -2
  123. package/dist/declarations/src/rx/util/identity.d.ts.map +0 -1
  124. package/dist/declarations/src/rx/util/observableToPromise.d.ts +0 -10
  125. package/dist/declarations/src/rx/util/observableToPromise.d.ts.map +0 -1
  126. package/dist/declarations/src/rx/util/pipe.d.ts +0 -4
  127. package/dist/declarations/src/rx/util/pipe.d.ts.map +0 -1
  128. package/dist/httpUtils-299a66f6.cjs.prod.js +0 -89
  129. package/dist/httpUtils-a1426e14.cjs.dev.js +0 -89
  130. package/dist/httpUtils-e45c9056.esm.js +0 -87
  131. package/dist/observable-01534ea8.esm.js +0 -102
  132. package/dist/observable-9aad8c3e.cjs.dev.js +0 -104
  133. package/dist/observable-ccb54234.cjs.prod.js +0 -104
  134. package/dist/share-5a8c2543.cjs.prod.js +0 -106
  135. package/dist/share-ca585761.esm.js +0 -104
  136. package/dist/share-f2ac9332.cjs.dev.js +0 -106
  137. package/dist/tap-2d565250.cjs.dev.js +0 -32
  138. package/dist/tap-606957cb.esm.js +0 -30
  139. package/dist/tap-d907998d.cjs.prod.js +0 -32
  140. package/dist/trpc-client.cjs.d.ts +0 -1
  141. package/dist/trpc-client.cjs.dev.js +0 -300
  142. package/dist/trpc-client.cjs.js +0 -7
  143. package/dist/trpc-client.cjs.prod.js +0 -300
  144. package/dist/trpc-client.esm.js +0 -295
  145. package/links/httpBatchLink/package.json +0 -4
  146. package/links/httpLink/package.json +0 -4
  147. package/links/loggerLink/package.json +0 -4
  148. package/links/splitLink/package.json +0 -4
  149. package/links/transformerLink/dist/trpc-client-links-transformerLink.cjs.d.ts +0 -1
  150. package/links/transformerLink/dist/trpc-client-links-transformerLink.cjs.dev.js +0 -67
  151. package/links/transformerLink/dist/trpc-client-links-transformerLink.cjs.js +0 -7
  152. package/links/transformerLink/dist/trpc-client-links-transformerLink.cjs.prod.js +0 -67
  153. package/links/transformerLink/dist/trpc-client-links-transformerLink.esm.js +0 -63
  154. package/links/transformerLink/package.json +0 -4
  155. package/links/wsLink/package.json +0 -4
  156. package/rx/dist/trpc-client-rx.cjs.d.ts +0 -1
  157. package/rx/dist/trpc-client-rx.cjs.dev.js +0 -9
  158. package/rx/dist/trpc-client-rx.cjs.js +0 -7
  159. package/rx/dist/trpc-client-rx.cjs.prod.js +0 -9
  160. package/rx/dist/trpc-client-rx.esm.js +0 -1
  161. package/rx/operators/dist/trpc-client-rx-operators.cjs.d.ts +0 -1
  162. package/rx/operators/dist/trpc-client-rx-operators.cjs.dev.js +0 -39
  163. package/rx/operators/dist/trpc-client-rx-operators.cjs.js +0 -7
  164. package/rx/operators/dist/trpc-client-rx-operators.cjs.prod.js +0 -39
  165. package/rx/operators/dist/trpc-client-rx-operators.esm.js +0 -33
  166. package/rx/operators/package.json +0 -4
  167. package/rx/package.json +0 -4
  168. package/src/internals/transformRPCResponse.ts +0 -25
  169. package/src/links/httpUtils.ts +0 -94
  170. package/src/links/transformerLink.ts +0 -70
  171. package/src/rx/index.ts +0 -2
  172. package/src/rx/observable.test.ts +0 -83
  173. package/src/rx/observable.ts +0 -70
  174. package/src/rx/operators/index.ts +0 -3
  175. package/src/rx/operators/map.test.ts +0 -92
  176. package/src/rx/operators/map.ts +0 -25
  177. package/src/rx/operators/share.test.ts +0 -60
  178. package/src/rx/operators/share.ts +0 -67
  179. package/src/rx/operators/tap.ts +0 -26
  180. package/src/rx/types.ts +0 -69
  181. package/src/rx/util/identity.ts +0 -3
  182. package/src/rx/util/observableToPromise.ts +0 -49
  183. package/src/rx/util/pipe.ts +0 -22
@@ -1,42 +1,42 @@
1
1
  import {
2
2
  AnyRouter,
3
+ ClientDataTransformerOptions,
4
+ DataTransformer,
3
5
  inferHandlerInput,
4
6
  inferProcedureInput,
5
7
  inferProcedureOutput,
6
8
  inferSubscriptionOutput,
7
9
  } from '@trpc/server';
8
- import { TRPCResult } from '@trpc/server/rpc';
10
+ import {
11
+ Observer,
12
+ Unsubscribable,
13
+ inferObservableValue,
14
+ observableToPromise,
15
+ share,
16
+ } from '@trpc/server/observable';
17
+ import { TRPCResultMessage } from '@trpc/server/rpc';
9
18
  import { CancelFn } from '..';
19
+ import { TRPCClientError } from '../TRPCClientError';
10
20
  import { getFetch } from '../getFetch';
11
- import { httpBatchLink } from '../links/httpBatchLink';
21
+ import { httpBatchLink } from '../links';
12
22
  import { createChain } from '../links/internals/createChain';
13
- import { transformOperationResult } from '../links/internals/transformOperationResult';
23
+ import {
24
+ transformOperationResult,
25
+ transformSubscriptionOperationResult,
26
+ } from '../links/internals/transformOperationResult';
14
27
  import {
15
28
  HTTPHeaders,
16
- LinkRuntime,
17
29
  OperationContext,
18
30
  OperationLink,
31
+ TRPCClientRuntime,
19
32
  TRPCLink,
20
33
  } from '../links/types';
21
- import { UnsubscribeFn } from '../rx';
22
- import { inferObservableValue } from '../rx/observable';
23
- import { share } from '../rx/operators';
24
- import { Observer } from '../rx/types';
25
- import { observableToPromise } from '../rx/util/observableToPromise';
26
- import { TRPCClientError } from '../TRPCClientError';
27
34
  import { getAbortController } from './fetchHelpers';
28
35
 
29
36
  type CancellablePromise<T = unknown> = Promise<T> & {
30
37
  cancel: CancelFn;
31
38
  };
32
39
 
33
- /**
34
- * @deprecated no longer used
35
- */
36
- export interface FetchOptions {
37
- fetch?: typeof fetch;
38
- AbortController?: typeof AbortController;
39
- }
40
40
  let idCounter = 0;
41
41
  function getRequestId() {
42
42
  return ++idCounter;
@@ -54,6 +54,11 @@ interface CreateTRPCClientBaseOptions {
54
54
  * headers to be set on outgoing requests / callback that of said headers
55
55
  */
56
56
  headers?: HTTPHeaders | (() => HTTPHeaders | Promise<HTTPHeaders>);
57
+ /**
58
+ * Data transformer
59
+ * @link https://trpc.io/docs/data-transformers
60
+ **/
61
+ transformer?: ClientDataTransformerOptions;
57
62
  }
58
63
 
59
64
  /** @internal */
@@ -69,7 +74,7 @@ export interface CreateTRPCClientWithURLOptions
69
74
  export interface CreateTRPCClientWithLinksOptions<TRouter extends AnyRouter>
70
75
  extends CreateTRPCClientBaseOptions {
71
76
  /**
72
- * @link http://localhost:3000/docs/links
77
+ * @link https://trpc.io/docs/links
73
78
  **/
74
79
  links: TRPCLink<TRouter>[];
75
80
  }
@@ -88,23 +93,37 @@ export type CreateTRPCClientOptions<TRouter extends AnyRouter> =
88
93
  | CreateTRPCClientWithURLOptions;
89
94
  export class TRPCClient<TRouter extends AnyRouter> {
90
95
  private readonly links: OperationLink<TRouter>[];
91
- public readonly runtime: LinkRuntime;
96
+ public readonly runtime: TRPCClientRuntime;
92
97
 
93
98
  constructor(opts: CreateTRPCClientOptions<TRouter>) {
94
99
  const _fetch = getFetch(opts?.fetch);
95
100
  const AC = getAbortController(opts?.AbortController);
96
101
 
97
- function getHeadersFn(): LinkRuntime['headers'] {
102
+ function getHeadersFn(): TRPCClientRuntime['headers'] {
98
103
  if (opts.headers) {
99
104
  const headers = opts.headers;
100
105
  return typeof headers === 'function' ? headers : () => headers;
101
106
  }
102
107
  return () => ({});
103
108
  }
109
+
110
+ const transformer: DataTransformer = opts.transformer
111
+ ? 'input' in opts.transformer
112
+ ? {
113
+ serialize: opts.transformer.input.serialize,
114
+ deserialize: opts.transformer.output.deserialize,
115
+ }
116
+ : opts.transformer
117
+ : {
118
+ serialize: (data) => data,
119
+ deserialize: (data) => data,
120
+ };
121
+
104
122
  this.runtime = {
105
123
  AbortController: AC as any,
106
124
  fetch: _fetch,
107
125
  headers: getHeadersFn(),
126
+ transformer,
108
127
  };
109
128
 
110
129
  if ('links' in opts) {
@@ -155,9 +174,9 @@ export class TRPCClient<TRouter extends AnyRouter> {
155
174
  (resolve, reject) => {
156
175
  promise
157
176
  .then((result) => {
158
- const transformed = transformOperationResult(result);
177
+ const transformed = transformOperationResult(result, this.runtime);
159
178
  if (transformed.ok) {
160
- resolve(transformed.data as any);
179
+ resolve(transformed.data);
161
180
  return;
162
181
  }
163
182
  reject(transformed.error);
@@ -189,7 +208,6 @@ export class TRPCClient<TRouter extends AnyRouter> {
189
208
  context,
190
209
  });
191
210
  }
192
-
193
211
  public mutation<
194
212
  TMutations extends TRouter['_def']['mutations'],
195
213
  TPath extends string & keyof TMutations,
@@ -217,25 +235,26 @@ export class TRPCClient<TRouter extends AnyRouter> {
217
235
  path: TPath,
218
236
  input: TInput,
219
237
  opts: TRPCRequestOptions &
220
- Partial<Observer<TRPCResult<TOutput>, TRPCClientError<TRouter>>>,
221
- ): UnsubscribeFn {
238
+ Partial<Observer<TRPCResultMessage<TOutput>, TRPCClientError<TRouter>>>,
239
+ ): Unsubscribable {
222
240
  const observable$ = this.$request<TInput, TOutput>({
223
241
  type: 'subscription',
224
242
  path,
225
243
  input,
226
244
  context: opts.context,
227
245
  });
228
- const observer = observable$.subscribe({
246
+ const runtime = this.runtime;
247
+ return observable$.subscribe({
229
248
  next(result) {
230
- if ('error' in result.data) {
231
- const err = TRPCClientError.from(result.data, {
232
- meta: result.context,
233
- });
234
-
235
- opts.error?.(err);
249
+ const transformed = transformSubscriptionOperationResult(
250
+ result,
251
+ runtime,
252
+ );
253
+ if (transformed.ok) {
254
+ opts.next?.(transformed.data);
236
255
  return;
237
256
  }
238
- opts.next?.(result.data.result);
257
+ opts.error?.(transformed.error);
239
258
  },
240
259
  error(err) {
241
260
  opts.error?.(err);
@@ -244,8 +263,5 @@ export class TRPCClient<TRouter extends AnyRouter> {
244
263
  opts.complete?.();
245
264
  },
246
265
  });
247
- return () => {
248
- observer.unsubscribe();
249
- };
250
266
  }
251
267
  }
@@ -1,18 +1,32 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
1
2
  import { CancelFn, PromiseAndCancel } from '../links/types';
2
3
 
3
4
  type BatchItem<TKey, TValue> = {
4
- cancelled: boolean;
5
+ aborted: boolean;
5
6
  key: TKey;
6
7
  resolve: (value: TValue) => void;
7
8
  reject: (error: Error) => void;
9
+ batch: Batch<TKey, TValue> | null;
8
10
  };
9
11
  type Batch<TKey, TValue> = {
10
12
  items: BatchItem<TKey, TValue>[];
11
13
  cancel: CancelFn;
12
14
  };
13
- type BatchLoadFn<TKey, TValue> = (keys: TKey[]) => {
14
- promise: Promise<TValue[]>;
15
- cancel: CancelFn;
15
+ type BatchLoader<TKey, TValue> = {
16
+ validate: (keys: TKey[]) => boolean;
17
+ fetch: (keys: TKey[]) => {
18
+ promise: Promise<TValue[]>;
19
+ cancel: CancelFn;
20
+ };
21
+ };
22
+
23
+ /**
24
+ * A function that should never be called unless we messed something up.
25
+ */
26
+ const throwFatalError = () => {
27
+ throw new Error(
28
+ 'Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new',
29
+ );
16
30
  };
17
31
 
18
32
  /**
@@ -20,67 +34,128 @@ type BatchLoadFn<TKey, TValue> = (keys: TKey[]) => {
20
34
  * Less configuration, no caching, and allows you to cancel requests
21
35
  * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled
22
36
  */
23
- export function dataLoader<TKey, TValue>(fetchMany: BatchLoadFn<TKey, TValue>) {
24
- let batch: Batch<TKey, TValue> | null = null;
25
- let dispatchTimer: NodeJS.Timer | number | null = null;
37
+ export function dataLoader<TKey, TValue>(
38
+ batchLoader: BatchLoader<TKey, TValue>,
39
+ ) {
40
+ let pendingItems: BatchItem<TKey, TValue>[] | null = null;
41
+ let dispatchTimer: ReturnType<typeof setTimeout> | null = null;
26
42
 
27
- const destroyTimerAndBatch = () => {
43
+ const destroyTimerAndPendingItems = () => {
28
44
  clearTimeout(dispatchTimer as any);
29
45
  dispatchTimer = null;
30
- batch = null;
46
+ pendingItems = null;
31
47
  };
48
+
49
+ /**
50
+ * Iterate through the items and split them into groups based on the `batchLoader`'s validate function
51
+ */
52
+ function groupItems(items: BatchItem<TKey, TValue>[]) {
53
+ const groupedItems: BatchItem<TKey, TValue>[][] = [[]];
54
+ let index = 0;
55
+ while (true) {
56
+ const item = items[index];
57
+ if (!item) {
58
+ // we're done
59
+ break;
60
+ }
61
+ const lastGroup = groupedItems[groupedItems.length - 1];
62
+
63
+ if (item.aborted) {
64
+ // Item was aborted before it was dispatched
65
+ item.reject(new Error('Aborted'));
66
+ index++;
67
+ continue;
68
+ }
69
+
70
+ const isValid = batchLoader.validate(
71
+ lastGroup.concat(item).map((it) => it.key),
72
+ );
73
+
74
+ if (isValid) {
75
+ lastGroup.push(item);
76
+ index++;
77
+ continue;
78
+ }
79
+
80
+ if (lastGroup.length === 0) {
81
+ item.reject(new Error('Input is too big for a single dispatch'));
82
+ index++;
83
+ continue;
84
+ }
85
+ // Create new group, next iteration will try to add the item to that
86
+ groupedItems.push([]);
87
+ }
88
+ return groupedItems;
89
+ }
90
+
32
91
  function dispatch() {
33
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
34
- const batchCopy = batch!;
35
- destroyTimerAndBatch();
36
- const { promise, cancel } = fetchMany(batchCopy.items.map((v) => v.key));
37
- batchCopy.cancel = cancel;
38
-
39
- promise
40
- .then((result) => {
41
- for (let i = 0; i < result.length; i++) {
42
- const value = result[i];
43
- batchCopy.items[i].resolve(value);
44
- }
45
- })
46
- .catch((cause) => {
47
- for (const item of batchCopy.items) {
48
- item.reject(cause);
49
- }
50
- });
92
+ const groupedItems = groupItems(pendingItems!);
93
+ destroyTimerAndPendingItems();
94
+
95
+ // Create batches for each group of items
96
+ for (const items of groupedItems) {
97
+ if (!items.length) {
98
+ continue;
99
+ }
100
+ const batch: Batch<TKey, TValue> = {
101
+ items,
102
+ cancel: throwFatalError,
103
+ };
104
+ for (const item of items) {
105
+ item.batch = batch;
106
+ }
107
+ const { promise, cancel } = batchLoader.fetch(
108
+ batch.items.map((_item) => _item.key),
109
+ );
110
+ batch.cancel = cancel;
111
+
112
+ promise
113
+ .then((result) => {
114
+ for (let i = 0; i < result.length; i++) {
115
+ const value = result[i];
116
+ const item = batch.items[i];
117
+ item.resolve(value);
118
+ item.batch = null;
119
+ }
120
+ })
121
+ .catch((cause) => {
122
+ for (const item of batch.items) {
123
+ item.reject(cause);
124
+ item.batch = null;
125
+ }
126
+ });
127
+ }
51
128
  }
52
129
  function load(key: TKey): PromiseAndCancel<TValue> {
53
- const batchItem = {
54
- cancelled: false,
130
+ const item: BatchItem<TKey, TValue> = {
131
+ aborted: false,
55
132
  key,
133
+ batch: null,
134
+ resolve: throwFatalError,
135
+ reject: throwFatalError,
56
136
  };
57
137
 
58
- if (!batch) {
59
- batch = {
60
- items: [],
61
- cancel() {
62
- destroyTimerAndBatch();
63
- },
64
- };
65
- }
66
- const thisBatch = batch;
67
138
  const promise = new Promise<TValue>((resolve, reject) => {
68
- const item = batchItem as any as BatchItem<TKey, TValue>;
69
139
  item.reject = reject;
70
140
  item.resolve = resolve;
71
- thisBatch.items.push(item);
141
+
142
+ if (!pendingItems) {
143
+ pendingItems = [];
144
+ }
145
+ pendingItems.push(item);
72
146
  });
147
+
73
148
  if (!dispatchTimer) {
74
149
  dispatchTimer = setTimeout(dispatch);
75
150
  }
76
151
  const cancel = () => {
77
- batchItem.cancelled = true;
152
+ item.aborted = true;
78
153
 
79
- if (thisBatch.items.some((item) => !item.cancelled)) {
80
- // there are still things that can be resolved
81
- return;
154
+ if (item.batch?.items.every((item) => item.aborted)) {
155
+ // All items in the batch have been cancelled
156
+ item.batch.cancel();
157
+ item.batch = null;
82
158
  }
83
- thisBatch.cancel();
84
159
  };
85
160
 
86
161
  return { promise, cancel };
@@ -1,7 +1,7 @@
1
1
  import { waitFor } from '@testing-library/dom';
2
2
  import { AnyRouter } from '@trpc/server';
3
+ import { observable } from '@trpc/server/observable';
3
4
  import { OperationLink } from '..';
4
- import { observable } from '../rx/observable';
5
5
  import { dedupeLink } from './dedupeLink';
6
6
  import { createChain } from './internals/createChain';
7
7
 
@@ -1,7 +1,5 @@
1
1
  import { AnyRouter } from '@trpc/server';
2
- import { observable } from '../rx/observable';
3
- import { share } from '../rx/operators';
4
- import { Observable } from '../rx/types';
2
+ import { Observable, observable, share } from '@trpc/server/observable';
5
3
  import { TRPCLink } from './types';
6
4
 
7
5
  export function dedupeLink<
@@ -28,7 +26,7 @@ export function dedupeLink<
28
26
  function reset() {
29
27
  delete pending[key];
30
28
  }
31
- const next$ = next(op).subscribe({
29
+ const subscription = next(op).subscribe({
32
30
  next(v) {
33
31
  observer.next(v);
34
32
  },
@@ -43,7 +41,7 @@ export function dedupeLink<
43
41
  });
44
42
  return () => {
45
43
  reset();
46
- next$.unsubscribe();
44
+ subscription.unsubscribe();
47
45
  };
48
46
  }).pipe(share());
49
47
  pending[key] = shared$;
@@ -1,47 +1,80 @@
1
1
  import { AnyRouter, ProcedureType } from '@trpc/server';
2
+ import { observable } from '@trpc/server/observable';
2
3
  import { dataLoader } from '../internals/dataLoader';
3
- import { observable } from '../rx/observable';
4
+ import {
5
+ HTTPLinkOptions,
6
+ ResponseShape,
7
+ getUrl,
8
+ httpRequest,
9
+ } from './internals/httpUtils';
4
10
  import { TRPCLink } from './types';
5
- import { HTTPLinkOptions, httpRequest, ResponseShape } from './httpUtils';
11
+
12
+ export interface HttpBatchLinkOptions extends HTTPLinkOptions {
13
+ maxURLLength?: number;
14
+ }
6
15
 
7
16
  export function httpBatchLink<TRouter extends AnyRouter>(
8
- opts: HTTPLinkOptions,
17
+ opts: HttpBatchLinkOptions,
9
18
  ): TRPCLink<TRouter> {
10
- const { url } = opts;
19
+ // initialized config
11
20
  return (runtime) => {
12
- type Key = { id: number; path: string; input: unknown };
13
- const fetcher = (type: ProcedureType) => (keyInputPairs: Key[]) => {
14
- const path = keyInputPairs.map((op) => op.path).join(',');
15
- const inputs = keyInputPairs.map((op) => op.input);
21
+ type BatchOperation = { id: number; path: string; input: unknown };
16
22
 
17
- const { promise, cancel } = httpRequest({
18
- url,
19
- inputs,
20
- path,
21
- runtime,
22
- type,
23
- });
23
+ const maxURLLength = opts.maxURLLength || Infinity;
24
+
25
+ const batchLoader = (type: ProcedureType) => {
26
+ const validate = (batchOps: BatchOperation[]) => {
27
+ if (maxURLLength === Infinity) {
28
+ // escape hatch for quick calcs
29
+ return true;
30
+ }
31
+ const path = batchOps.map((op) => op.path).join(',');
32
+ const inputs = batchOps.map((op) => op.input);
33
+
34
+ const url = getUrl({ url: opts.url, runtime, type, path, inputs });
35
+ return url.length <= maxURLLength;
36
+ };
37
+
38
+ const fetch = (batchOps: BatchOperation[]) => {
39
+ const path = batchOps.map((op) => op.path).join(',');
40
+ const inputs = batchOps.map((op) => op.input);
24
41
 
25
- return {
26
- promise: promise.then((res) => {
27
- const resJSON = Array.isArray(res.json)
28
- ? res.json
29
- : keyInputPairs.map(() => res.json);
42
+ const { promise, cancel } = httpRequest({
43
+ url: opts.url,
44
+ runtime,
45
+ type,
46
+ path,
47
+ inputs,
48
+ });
30
49
 
31
- const result = resJSON.map((item) => ({
32
- meta: res.meta,
33
- json: item,
34
- }));
50
+ return {
51
+ promise: promise.then((res) => {
52
+ const resJSON = Array.isArray(res.json)
53
+ ? res.json
54
+ : batchOps.map(() => res.json);
35
55
 
36
- return result;
37
- }),
38
- cancel,
56
+ const result = resJSON.map((item) => ({
57
+ meta: res.meta,
58
+ json: item,
59
+ }));
60
+
61
+ return result;
62
+ }),
63
+ cancel,
64
+ };
39
65
  };
66
+
67
+ return { validate, fetch };
40
68
  };
41
- const query = dataLoader<Key, ResponseShape>(fetcher('query'));
42
- const mutation = dataLoader<Key, ResponseShape>(fetcher('mutation'));
43
- const subscription = dataLoader<Key, ResponseShape>(
44
- fetcher('subscription'),
69
+
70
+ const query = dataLoader<BatchOperation, ResponseShape>(
71
+ batchLoader('query'),
72
+ );
73
+ const mutation = dataLoader<BatchOperation, ResponseShape>(
74
+ batchLoader('mutation'),
75
+ );
76
+ const subscription = dataLoader<BatchOperation, ResponseShape>(
77
+ batchLoader('subscription'),
45
78
  );
46
79
 
47
80
  const loaders = { query, subscription, mutation };
@@ -1,7 +1,7 @@
1
1
  import { AnyRouter } from '@trpc/server';
2
- import { observable } from '../rx/observable';
2
+ import { observable } from '@trpc/server/observable';
3
+ import { HTTPLinkOptions, httpRequest } from './internals/httpUtils';
3
4
  import { TRPCLink } from './types';
4
- import { HTTPLinkOptions, httpRequest } from './httpUtils';
5
5
 
6
6
  export function httpLink<TRouter extends AnyRouter>(
7
7
  opts: HTTPLinkOptions,
@@ -12,11 +12,11 @@ export function httpLink<TRouter extends AnyRouter>(
12
12
  observable((observer) => {
13
13
  const { path, input, type } = op;
14
14
  const { promise, cancel } = httpRequest({
15
+ url,
15
16
  runtime,
17
+ type,
16
18
  path,
17
19
  input,
18
- type,
19
- url,
20
20
  });
21
21
  promise
22
22
  .then((res) => {
@@ -0,0 +1,8 @@
1
+ export * from './dedupeLink';
2
+ export * from './httpBatchLink';
3
+ export * from './httpLink';
4
+ export * from './loggerLink';
5
+ export * from './retryLink';
6
+ export * from './splitLink';
7
+ export * from './wsLink';
8
+ export * from './types';
@@ -1,6 +1,6 @@
1
+ import { observable } from '@trpc/server/observable';
1
2
  import { AnyRouter } from '@trpc/server/src';
2
3
  import { createChain } from './createChain';
3
- import { observable } from '../../rx/observable';
4
4
 
5
5
  describe('chain', () => {
6
6
  test('trivial', () => {
@@ -8,9 +8,9 @@ describe('chain', () => {
8
8
  links: [
9
9
  ({ next, op }) => {
10
10
  return observable((observer) => {
11
- const next$ = next(op).subscribe(observer);
11
+ const subscription = next(op).subscribe(observer);
12
12
  return () => {
13
- next$.unsubscribe();
13
+ subscription.unsubscribe();
14
14
  };
15
15
  });
16
16
  },
@@ -62,9 +62,9 @@ describe('chain', () => {
62
62
  },
63
63
  },
64
64
  });
65
- const next$ = next(op).subscribe(observer);
65
+ const subscription = next(op).subscribe(observer);
66
66
  return () => {
67
- next$.unsubscribe();
67
+ subscription.unsubscribe();
68
68
  };
69
69
  });
70
70
  },
@@ -1,5 +1,5 @@
1
1
  import { AnyRouter } from '@trpc/server';
2
- import { observable } from '../../rx/observable';
2
+ import { observable } from '@trpc/server/observable';
3
3
  import { Operation, OperationLink, OperationResultObservable } from '../types';
4
4
 
5
5
  /** @internal */
@@ -14,7 +14,7 @@ export function createChain<
14
14
  return observable((observer) => {
15
15
  function execute(index = 0, op = opts.op) {
16
16
  const next = opts.links[index];
17
- const next$ = next({
17
+ const subscription = next({
18
18
  op,
19
19
  next(nextOp) {
20
20
  const nextObserver = execute(index + 1, nextOp);
@@ -22,7 +22,7 @@ export function createChain<
22
22
  return nextObserver;
23
23
  },
24
24
  });
25
- return next$;
25
+ return subscription;
26
26
  }
27
27
 
28
28
  const obs$ = execute();