@data-client/core 0.1.0 → 0.2.1

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 (247) hide show
  1. package/dist/index.js +134 -409
  2. package/dist/index.umd.min.js +1 -1
  3. package/dist/next.js +61 -101
  4. package/legacy/actionTypes.js +2 -2
  5. package/legacy/controller/Controller.js +276 -6
  6. package/legacy/controller/createFetch.js +3 -14
  7. package/legacy/controller/createInvalidate.js +1 -1
  8. package/legacy/controller/createInvalidateAll.js +1 -1
  9. package/legacy/controller/createOptimistic.js +1 -7
  10. package/legacy/controller/createReset.js +1 -1
  11. package/legacy/controller/createSet.js +31 -0
  12. package/legacy/controller/createSubscription.js +3 -7
  13. package/legacy/index.js +2 -5
  14. package/legacy/internal.js +2 -2
  15. package/legacy/manager/DevtoolsManager.js +2 -2
  16. package/legacy/manager/LogoutManager.js +2 -2
  17. package/legacy/manager/NetworkManager.js +28 -59
  18. package/legacy/manager/PollingSubscription.js +18 -27
  19. package/legacy/manager/SubscriptionManager.js +16 -42
  20. package/legacy/manager/applyManager.js +2 -1
  21. package/legacy/middlewareTypes.js +1 -1
  22. package/legacy/newActions.js +1 -1
  23. package/legacy/next/index.js +3 -3
  24. package/legacy/state/reducer/createReducer.js +2 -6
  25. package/legacy/state/reducer/fetchReducer.js +3 -13
  26. package/legacy/state/reducer/invalidateReducer.js +1 -1
  27. package/legacy/state/reducer/setReducer.js +9 -16
  28. package/legacy/types.js +2 -6
  29. package/lib/actionTypes.d.ts +1 -0
  30. package/lib/actionTypes.d.ts.map +1 -1
  31. package/lib/actionTypes.js +2 -2
  32. package/lib/controller/Controller.d.ts +126 -6
  33. package/lib/controller/Controller.d.ts.map +1 -1
  34. package/lib/controller/Controller.js +276 -6
  35. package/lib/controller/createFetch.d.ts +2 -2
  36. package/lib/controller/createFetch.d.ts.map +1 -1
  37. package/lib/controller/createFetch.js +3 -14
  38. package/lib/controller/createInvalidate.d.ts +1 -1
  39. package/lib/controller/createInvalidate.d.ts.map +1 -1
  40. package/lib/controller/createInvalidate.js +1 -1
  41. package/lib/controller/createInvalidateAll.d.ts +1 -1
  42. package/lib/controller/createInvalidateAll.d.ts.map +1 -1
  43. package/lib/controller/createInvalidateAll.js +1 -1
  44. package/lib/controller/createOptimistic.d.ts +2 -2
  45. package/lib/controller/createOptimistic.d.ts.map +1 -1
  46. package/lib/controller/createOptimistic.js +1 -7
  47. package/lib/controller/createReset.d.ts +1 -1
  48. package/lib/controller/createReset.d.ts.map +1 -1
  49. package/lib/controller/createReset.js +1 -1
  50. package/lib/controller/{createReceive.d.ts → createSet.d.ts} +6 -6
  51. package/lib/controller/createSet.d.ts.map +1 -0
  52. package/lib/controller/createSet.js +31 -0
  53. package/lib/controller/createSubscription.d.ts +3 -3
  54. package/lib/controller/createSubscription.d.ts.map +1 -1
  55. package/lib/controller/createSubscription.js +3 -7
  56. package/lib/index.d.ts +2 -6
  57. package/lib/index.d.ts.map +1 -1
  58. package/lib/index.js +2 -5
  59. package/lib/internal.d.ts +1 -1
  60. package/lib/internal.d.ts.map +1 -1
  61. package/lib/internal.js +2 -2
  62. package/lib/manager/DevtoolsManager.d.ts +1 -1
  63. package/lib/manager/DevtoolsManager.js +2 -2
  64. package/lib/manager/LogoutManager.d.ts +4 -5
  65. package/lib/manager/LogoutManager.d.ts.map +1 -1
  66. package/lib/manager/LogoutManager.js +2 -2
  67. package/lib/manager/NetworkManager.d.ts +4 -5
  68. package/lib/manager/NetworkManager.d.ts.map +1 -1
  69. package/lib/manager/NetworkManager.js +28 -61
  70. package/lib/manager/PollingSubscription.d.ts +9 -9
  71. package/lib/manager/PollingSubscription.d.ts.map +1 -1
  72. package/lib/manager/PollingSubscription.js +18 -27
  73. package/lib/manager/SubscriptionManager.d.ts +10 -15
  74. package/lib/manager/SubscriptionManager.d.ts.map +1 -1
  75. package/lib/manager/SubscriptionManager.js +16 -42
  76. package/lib/manager/applyManager.d.ts.map +1 -1
  77. package/lib/manager/applyManager.js +2 -1
  78. package/lib/middlewareTypes.d.ts +5 -5
  79. package/lib/middlewareTypes.d.ts.map +1 -1
  80. package/lib/middlewareTypes.js +1 -1
  81. package/lib/newActions.d.ts +26 -18
  82. package/lib/newActions.d.ts.map +1 -1
  83. package/lib/newActions.js +1 -1
  84. package/lib/next/index.d.ts +2 -2
  85. package/lib/next/index.d.ts.map +1 -1
  86. package/lib/next/index.js +3 -3
  87. package/lib/state/reducer/createReducer.d.ts.map +1 -1
  88. package/lib/state/reducer/createReducer.js +2 -6
  89. package/lib/state/reducer/fetchReducer.d.ts +1 -2
  90. package/lib/state/reducer/fetchReducer.d.ts.map +1 -1
  91. package/lib/state/reducer/fetchReducer.js +3 -14
  92. package/lib/state/reducer/invalidateReducer.d.ts +3 -4
  93. package/lib/state/reducer/invalidateReducer.d.ts.map +1 -1
  94. package/lib/state/reducer/invalidateReducer.js +1 -1
  95. package/lib/state/reducer/setReducer.d.ts +2 -38
  96. package/lib/state/reducer/setReducer.d.ts.map +1 -1
  97. package/lib/state/reducer/setReducer.js +9 -17
  98. package/lib/types.d.ts +9 -30
  99. package/lib/types.d.ts.map +1 -1
  100. package/lib/types.js +2 -6
  101. package/package.json +10 -7
  102. package/src/actionTypes.ts +1 -1
  103. package/src/controller/Controller.ts +491 -10
  104. package/src/controller/createFetch.ts +4 -19
  105. package/src/controller/createInvalidate.ts +1 -1
  106. package/src/controller/createInvalidateAll.ts +1 -1
  107. package/src/controller/createOptimistic.ts +3 -9
  108. package/src/controller/createReset.ts +1 -1
  109. package/src/controller/{createReceive.ts → createSet.ts} +9 -17
  110. package/src/controller/createSubscription.ts +3 -10
  111. package/src/index.ts +2 -16
  112. package/src/internal.ts +1 -1
  113. package/src/manager/DevtoolsManager.ts +1 -1
  114. package/src/manager/LogoutManager.ts +4 -5
  115. package/src/manager/NetworkManager.ts +31 -80
  116. package/src/manager/PollingSubscription.ts +40 -38
  117. package/src/manager/SubscriptionManager.ts +22 -54
  118. package/src/manager/__tests__/__snapshots__/pollingSubscription.ts.snap +10 -8
  119. package/src/manager/__tests__/logoutManager.ts +5 -5
  120. package/src/manager/__tests__/manager.ts +2 -4
  121. package/src/manager/__tests__/networkManager.ts +8 -42
  122. package/src/manager/__tests__/pollingSubscription.ts +259 -151
  123. package/src/manager/__tests__/subscriptionManager.ts +7 -13
  124. package/src/manager/applyManager.ts +1 -0
  125. package/src/middlewareTypes.ts +5 -10
  126. package/src/newActions.ts +33 -23
  127. package/src/next/index.ts +2 -2
  128. package/src/state/__tests__/reducer.ts +59 -297
  129. package/src/state/reducer/createReducer.ts +3 -11
  130. package/src/state/reducer/fetchReducer.ts +5 -18
  131. package/src/state/reducer/invalidateReducer.ts +2 -2
  132. package/src/state/reducer/setReducer.ts +10 -22
  133. package/src/types.ts +9 -78
  134. package/ts3.4/actionTypes.d.ts +1 -0
  135. package/ts3.4/controller/Controller.d.ts +168 -6
  136. package/ts3.4/controller/createFetch.d.ts +2 -2
  137. package/ts3.4/controller/createInvalidate.d.ts +1 -1
  138. package/ts3.4/controller/createInvalidateAll.d.ts +1 -1
  139. package/ts3.4/controller/createOptimistic.d.ts +1 -1
  140. package/ts3.4/controller/createReset.d.ts +1 -1
  141. package/ts3.4/controller/{createReceive.d.ts → createSet.d.ts} +6 -6
  142. package/ts3.4/controller/createSubscription.d.ts +3 -3
  143. package/ts3.4/index.d.ts +2 -7
  144. package/ts3.4/internal.d.ts +1 -1
  145. package/ts3.4/manager/DevtoolsManager.d.ts +1 -1
  146. package/ts3.4/manager/LogoutManager.d.ts +4 -5
  147. package/ts3.4/manager/NetworkManager.d.ts +4 -5
  148. package/ts3.4/manager/PollingSubscription.d.ts +9 -9
  149. package/ts3.4/manager/SubscriptionManager.d.ts +10 -15
  150. package/ts3.4/middlewareTypes.d.ts +5 -5
  151. package/ts3.4/newActions.d.ts +26 -18
  152. package/ts3.4/next/index.d.ts +2 -2
  153. package/ts3.4/state/reducer/fetchReducer.d.ts +1 -2
  154. package/ts3.4/state/reducer/invalidateReducer.d.ts +3 -4
  155. package/ts3.4/state/reducer/setReducer.d.ts +2 -38
  156. package/ts3.4/types.d.ts +8 -30
  157. package/legacy/compatibleActions.js +0 -2
  158. package/legacy/controller/BaseController.js +0 -289
  159. package/legacy/controller/createReceive.js +0 -36
  160. package/legacy/endpoint/index.js +0 -2
  161. package/legacy/endpoint/shapes.js +0 -2
  162. package/legacy/endpoint/types.js +0 -2
  163. package/legacy/legacyActions.js +0 -2
  164. package/legacy/next/Controller.js +0 -24
  165. package/legacy/previousActions.js +0 -2
  166. package/legacy/state/applyUpdatersToResults.js +0 -4
  167. package/legacy/state/legacy-actions/createFetch.js +0 -62
  168. package/legacy/state/legacy-actions/createReceive.js +0 -37
  169. package/legacy/state/legacy-actions/createReceiveError.js +0 -28
  170. package/legacy/state/legacy-actions/index.js +0 -4
  171. package/legacy/state/reducerInstance.js +0 -9
  172. package/lib/compatibleActions.d.ts +0 -47
  173. package/lib/compatibleActions.d.ts.map +0 -1
  174. package/lib/compatibleActions.js +0 -2
  175. package/lib/controller/BaseController.d.ts +0 -128
  176. package/lib/controller/BaseController.d.ts.map +0 -1
  177. package/lib/controller/BaseController.js +0 -289
  178. package/lib/controller/createReceive.d.ts.map +0 -1
  179. package/lib/controller/createReceive.js +0 -36
  180. package/lib/endpoint/index.d.ts +0 -3
  181. package/lib/endpoint/index.d.ts.map +0 -1
  182. package/lib/endpoint/index.js +0 -2
  183. package/lib/endpoint/shapes.d.ts +0 -25
  184. package/lib/endpoint/shapes.d.ts.map +0 -1
  185. package/lib/endpoint/shapes.js +0 -2
  186. package/lib/endpoint/types.d.ts +0 -45
  187. package/lib/endpoint/types.d.ts.map +0 -1
  188. package/lib/endpoint/types.js +0 -2
  189. package/lib/legacyActions.d.ts +0 -92
  190. package/lib/legacyActions.d.ts.map +0 -1
  191. package/lib/legacyActions.js +0 -2
  192. package/lib/next/Controller.d.ts +0 -14
  193. package/lib/next/Controller.d.ts.map +0 -1
  194. package/lib/next/Controller.js +0 -24
  195. package/lib/previousActions.d.ts +0 -91
  196. package/lib/previousActions.d.ts.map +0 -1
  197. package/lib/previousActions.js +0 -2
  198. package/lib/state/applyUpdatersToResults.d.ts +0 -13
  199. package/lib/state/applyUpdatersToResults.d.ts.map +0 -1
  200. package/lib/state/applyUpdatersToResults.js +0 -7
  201. package/lib/state/legacy-actions/createFetch.d.ts +0 -19
  202. package/lib/state/legacy-actions/createFetch.d.ts.map +0 -1
  203. package/lib/state/legacy-actions/createFetch.js +0 -62
  204. package/lib/state/legacy-actions/createReceive.d.ts +0 -14
  205. package/lib/state/legacy-actions/createReceive.d.ts.map +0 -1
  206. package/lib/state/legacy-actions/createReceive.js +0 -37
  207. package/lib/state/legacy-actions/createReceiveError.d.ts +0 -9
  208. package/lib/state/legacy-actions/createReceiveError.d.ts.map +0 -1
  209. package/lib/state/legacy-actions/createReceiveError.js +0 -28
  210. package/lib/state/legacy-actions/index.d.ts +0 -4
  211. package/lib/state/legacy-actions/index.d.ts.map +0 -1
  212. package/lib/state/legacy-actions/index.js +0 -4
  213. package/lib/state/reducerInstance.d.ts +0 -7
  214. package/lib/state/reducerInstance.d.ts.map +0 -1
  215. package/lib/state/reducerInstance.js +0 -9
  216. package/src/compatibleActions.ts +0 -96
  217. package/src/controller/BaseController.ts +0 -508
  218. package/src/endpoint/index.ts +0 -14
  219. package/src/endpoint/shapes.ts +0 -53
  220. package/src/endpoint/types.ts +0 -72
  221. package/src/legacyActions.ts +0 -163
  222. package/src/manager/__tests__/__snapshots__/pollingSubscription-endpoint.ts.snap +0 -49
  223. package/src/manager/__tests__/networkManager-legacy.ts +0 -394
  224. package/src/manager/__tests__/pollingSubscription-endpoint.ts +0 -423
  225. package/src/next/Controller.ts +0 -39
  226. package/src/previousActions.ts +0 -159
  227. package/src/state/__tests__/applyUpdatersToResults.ts +0 -40
  228. package/src/state/applyUpdatersToResults.ts +0 -29
  229. package/src/state/legacy-actions/createFetch.ts +0 -95
  230. package/src/state/legacy-actions/createReceive.ts +0 -68
  231. package/src/state/legacy-actions/createReceiveError.ts +0 -43
  232. package/src/state/legacy-actions/index.ts +0 -3
  233. package/src/state/reducerInstance.ts +0 -14
  234. package/ts3.4/compatibleActions.d.ts +0 -47
  235. package/ts3.4/controller/BaseController.d.ts +0 -170
  236. package/ts3.4/endpoint/index.d.ts +0 -3
  237. package/ts3.4/endpoint/shapes.d.ts +0 -25
  238. package/ts3.4/endpoint/types.d.ts +0 -45
  239. package/ts3.4/legacyActions.d.ts +0 -95
  240. package/ts3.4/next/Controller.d.ts +0 -14
  241. package/ts3.4/previousActions.d.ts +0 -94
  242. package/ts3.4/state/applyUpdatersToResults.d.ts +0 -13
  243. package/ts3.4/state/legacy-actions/createFetch.d.ts +0 -19
  244. package/ts3.4/state/legacy-actions/createReceive.d.ts +0 -14
  245. package/ts3.4/state/legacy-actions/createReceiveError.d.ts +0 -9
  246. package/ts3.4/state/legacy-actions/index.d.ts +0 -4
  247. package/ts3.4/state/reducerInstance.d.ts +0 -7
@@ -1,508 +0,0 @@
1
- import type {
2
- ErrorTypes,
3
- SnapshotInterface,
4
- DenormalizeCache,
5
- Schema,
6
- } from '@data-client/normalizr';
7
- import {
8
- WeakEntityMap,
9
- ExpiryStatus,
10
- EndpointInterface,
11
- FetchFunction,
12
- ResolveType,
13
- DenormalizeNullable,
14
- Path,
15
- denormalizeCached,
16
- isEntity,
17
- } from '@data-client/normalizr';
18
- import { inferResults, validateInference } from '@data-client/normalizr';
19
-
20
- import createInvalidate from './createInvalidate.js';
21
- import createInvalidateAll from './createInvalidateAll.js';
22
- import createReceive from './createReceive.js';
23
- import createReset from './createReset.js';
24
- import {
25
- createUnsubscription,
26
- createSubscription,
27
- } from './createSubscription.js';
28
- import type { EndpointUpdateFunction } from './types.js';
29
- import { initialState } from '../state/reducer/createReducer.js';
30
- import selectMeta from '../state/selectMeta.js';
31
- import type {
32
- ActionTypes as BroadActionTypes,
33
- CombinedActionTypes,
34
- State,
35
- } from '../types.js';
36
-
37
- export type GenericDispatch = (value: any) => Promise<void>;
38
- export type CompatibleDispatch = (value: CombinedActionTypes) => Promise<void>;
39
- type PreviousDispatch = (value: BroadActionTypes) => Promise<void>;
40
-
41
- interface ConstructorProps<D extends GenericDispatch = CompatibleDispatch> {
42
- dispatch?: D;
43
- getState?: () => State<unknown>;
44
- globalCache?: DenormalizeCache;
45
- }
46
-
47
- const unsetDispatch = (action: unknown): Promise<void> => {
48
- throw new Error(
49
- `Dispatching while constructing your middleware is not allowed. ` +
50
- `Other middleware would not be applied to this dispatch.`,
51
- );
52
- };
53
- const unsetState = (): State<unknown> => {
54
- // This is only the value until it is set by the CacheProvider
55
- /* istanbul ignore next */
56
- return initialState;
57
- };
58
-
59
- /**
60
- * Imperative control of Rest Hooks store
61
- * @see https://resthooks.io/docs/api/Controller
62
- */
63
- export default class Controller<
64
- D extends GenericDispatch = CompatibleDispatch,
65
- > {
66
- /**
67
- * Dispatches an action to Rest Hooks reducer.
68
- *
69
- * @see https://resthooks.io/docs/api/Controller#dispatch
70
- */
71
- declare readonly dispatch: D;
72
- /**
73
- * Gets the latest state snapshot that is fully committed.
74
- *
75
- * This can be useful for imperative use-cases like event handlers.
76
- * This should *not* be used to render; instead useSuspense() or useCache()
77
- * @see https://resthooks.io/docs/api/Controller#getState
78
- */
79
- declare readonly getState: () => State<unknown>;
80
- declare readonly globalCache: DenormalizeCache;
81
-
82
- constructor({
83
- dispatch = unsetDispatch as any,
84
- getState = unsetState,
85
- globalCache = {
86
- entities: {},
87
- results: {},
88
- },
89
- }: ConstructorProps<D> = {}) {
90
- this.dispatch = dispatch;
91
- this.getState = getState;
92
- this.globalCache = globalCache;
93
- }
94
-
95
- /*************** Action Dispatchers ***************/
96
-
97
- /**
98
- * Forces refetching and suspense on useSuspense with the same Endpoint and parameters.
99
- * @see https://resthooks.io/docs/api/Controller#invalidate
100
- */
101
- invalidate = <E extends EndpointInterface>(
102
- endpoint: E,
103
- ...args: readonly [...Parameters<E>] | readonly [null]
104
- ): Promise<void> =>
105
- args[0] !== null
106
- ? this.dispatch(
107
- createInvalidate(endpoint, {
108
- args: args as readonly [...Parameters<E>],
109
- }),
110
- )
111
- : Promise.resolve();
112
-
113
- /**
114
- * Forces refetching and suspense on useSuspense on all matching endpoint result keys.
115
- * @see https://resthooks.io/docs/api/Controller#invalidateAll
116
- */
117
- invalidateAll = (options: { testKey: (key: string) => boolean }) =>
118
- this.dispatch(createInvalidateAll((key: string) => options.testKey(key)));
119
-
120
- /**
121
- * Resets the entire Rest Hooks cache. All inflight requests will not resolve.
122
- * @see https://resthooks.io/docs/api/Controller#resetEntireStore
123
- */
124
- resetEntireStore = (): Promise<void> => this.dispatch(createReset());
125
-
126
- /**
127
- * Stores response in cache for given Endpoint and args.
128
- * @see https://resthooks.io/docs/api/Controller#set
129
- */
130
- setResponse = <
131
- E extends EndpointInterface & {
132
- update?: EndpointUpdateFunction<E>;
133
- },
134
- >(
135
- endpoint: E,
136
- ...rest: readonly [...Parameters<E>, any]
137
- ): Promise<void> => {
138
- const response: ResolveType<E> = rest[rest.length - 1];
139
- const action = createReceive(endpoint, {
140
- args: rest.slice(0, rest.length - 1) as Parameters<E>,
141
- response,
142
- });
143
- return this.dispatch(action);
144
- };
145
-
146
- // TODO: deprecate
147
- /**
148
- * Another name for setResponse
149
- * @see https://resthooks.io/docs/api/Controller#setResponse
150
- */
151
- /* istanbul ignore next */ receive = <
152
- E extends EndpointInterface & {
153
- update?: EndpointUpdateFunction<E>;
154
- },
155
- >(
156
- endpoint: E,
157
- ...rest: readonly [...Parameters<E>, any]
158
- ): Promise<void> => {
159
- /* istanbul ignore next */
160
- return this.setResponse(endpoint, ...rest);
161
- };
162
-
163
- /**
164
- * Stores the result of Endpoint and args as the error provided.
165
- * @see https://resthooks.io/docs/api/Controller#setError
166
- */
167
- setError = <
168
- E extends EndpointInterface & {
169
- update?: EndpointUpdateFunction<E>;
170
- },
171
- >(
172
- endpoint: E,
173
- ...rest: readonly [...Parameters<E>, Error]
174
- ): Promise<void> => {
175
- const response: Error = rest[rest.length - 1];
176
- const action = createReceive(endpoint, {
177
- args: rest.slice(0, rest.length - 1) as Parameters<E>,
178
- response,
179
- error: true,
180
- });
181
- return this.dispatch(action);
182
- };
183
-
184
- // TODO: deprecate
185
- /**
186
- * Another name for setError
187
- * @see https://resthooks.io/docs/api/Controller#setError
188
- */
189
- /* istanbul ignore next */ receiveError = <
190
- E extends EndpointInterface & {
191
- update?: EndpointUpdateFunction<E>;
192
- },
193
- >(
194
- endpoint: E,
195
- ...rest: readonly [...Parameters<E>, Error]
196
- ): Promise<void> => {
197
- /* istanbul ignore next */
198
- return this.setError(endpoint, ...rest);
199
- };
200
-
201
- /**
202
- * Resolves an inflight fetch. `fetchedAt` should `fetch`'s `createdAt`
203
- * @see https://resthooks.io/docs/api/Controller#resolve
204
- */
205
- resolve = <
206
- E extends EndpointInterface & {
207
- update?: EndpointUpdateFunction<E>;
208
- },
209
- >(
210
- endpoint: E,
211
- meta:
212
- | {
213
- args: readonly [...Parameters<E>];
214
- response: Error;
215
- fetchedAt: number;
216
- error: true;
217
- }
218
- | {
219
- args: readonly [...Parameters<E>];
220
- response: any;
221
- fetchedAt: number;
222
- error?: false;
223
- },
224
- ): Promise<void> => {
225
- return this.dispatch(createReceive(endpoint, meta as any));
226
- };
227
-
228
- /**
229
- * Marks a new subscription to a given Endpoint.
230
- * @see https://resthooks.io/docs/api/Controller#subscribe
231
- */
232
- subscribe = <
233
- E extends EndpointInterface<
234
- FetchFunction,
235
- Schema | undefined,
236
- undefined | false
237
- >,
238
- >(
239
- endpoint: E,
240
- ...args: readonly [...Parameters<E>] | readonly [null]
241
- ): Promise<void> =>
242
- args[0] !== null
243
- ? this.dispatch(
244
- createSubscription(endpoint, {
245
- args: args as readonly [...Parameters<E>],
246
- }),
247
- )
248
- : Promise.resolve();
249
-
250
- /**
251
- * Marks completion of subscription to a given Endpoint.
252
- * @see https://resthooks.io/docs/api/Controller#unsubscribe
253
- */
254
- unsubscribe = <
255
- E extends EndpointInterface<
256
- FetchFunction,
257
- Schema | undefined,
258
- undefined | false
259
- >,
260
- >(
261
- endpoint: E,
262
- ...args: readonly [...Parameters<E>] | readonly [null]
263
- ): Promise<void> =>
264
- args[0] !== null
265
- ? this.dispatch(
266
- createUnsubscription(endpoint, {
267
- args: args as readonly [...Parameters<E>],
268
- }),
269
- )
270
- : Promise.resolve();
271
-
272
- /*************** More ***************/
273
-
274
- /* TODO:
275
- abort = <E extends EndpointInterface>(
276
- endpoint: E,
277
- ...args: readonly [...Parameters<E>]
278
- ): Promise<void>
279
- */
280
-
281
- /**
282
- * Gets a snapshot (https://resthooks.io/docs/api/Snapshot)
283
- * @see https://resthooks.io/docs/api/Controller#snapshot
284
- */
285
- snapshot = (state: State<unknown>, fetchedAt?: number): SnapshotInterface => {
286
- return new Snapshot(this, state, fetchedAt);
287
- };
288
-
289
- /**
290
- * Gets the error, if any, for a given endpoint. Returns undefined for no errors.
291
- * @see https://resthooks.io/docs/api/Controller#getError
292
- */
293
- getError = <
294
- E extends Pick<EndpointInterface, 'key'>,
295
- Args extends readonly [...Parameters<E['key']>] | readonly [null],
296
- >(
297
- endpoint: E,
298
- ...rest: [...Args, State<unknown>]
299
- ): ErrorTypes | undefined => {
300
- if (rest[0] === null) return;
301
- const state = rest[rest.length - 1] as State<unknown>;
302
- // this is typescript generics breaking
303
- const args: any = rest.slice(0, rest.length - 1) as Parameters<E['key']>;
304
- const key = endpoint.key(...args);
305
-
306
- const meta = selectMeta(state, key);
307
- const results = state.results[key];
308
-
309
- if (results !== undefined && meta?.errorPolicy === 'soft') return;
310
-
311
- return meta?.error as any;
312
- };
313
-
314
- /**
315
- * Gets the (globally referentially stable) response for a given endpoint/args pair from state given.
316
- * @see https://resthooks.io/docs/api/Controller#getResponse
317
- */
318
- getResponse = <
319
- E extends Pick<EndpointInterface, 'key' | 'schema' | 'invalidIfStale'>,
320
- Args extends readonly [...Parameters<E['key']>] | readonly [null],
321
- >(
322
- endpoint: E,
323
- ...rest: [...Args, State<unknown>]
324
- ): {
325
- data: DenormalizeNullable<E['schema']>;
326
- expiryStatus: ExpiryStatus;
327
- expiresAt: number;
328
- } => {
329
- const state = rest[rest.length - 1] as State<unknown>;
330
- // this is typescript generics breaking
331
- const args: any = rest.slice(0, rest.length - 1) as Parameters<E['key']>;
332
- const isActive = args.length !== 1 || args[0] !== null;
333
- const key = isActive ? endpoint.key(...args) : '';
334
- const cacheResults = isActive ? state.results[key] : undefined;
335
- const schema = endpoint.schema;
336
- const meta = selectMeta(state, key);
337
- let expiresAt = meta?.expiresAt;
338
-
339
- let invalidResults = false;
340
- let results;
341
- if (cacheResults === undefined && endpoint.schema !== undefined) {
342
- results = inferResults(
343
- endpoint.schema,
344
- args,
345
- state.indexes,
346
- state.entities,
347
- );
348
- invalidResults = !validateInference(results);
349
- if (!expiresAt && invalidResults) expiresAt = 1;
350
- } else {
351
- results = cacheResults;
352
- }
353
-
354
- if (!isActive) {
355
- return {
356
- data: results as any,
357
- expiryStatus: ExpiryStatus.Valid,
358
- expiresAt: Infinity,
359
- };
360
- }
361
-
362
- if (!endpoint.schema || !schemaHasEntity(endpoint.schema)) {
363
- return {
364
- data: results,
365
- expiryStatus: meta?.invalidated
366
- ? ExpiryStatus.Invalid
367
- : cacheResults && !endpoint.invalidIfStale
368
- ? ExpiryStatus.Valid
369
- : ExpiryStatus.InvalidIfStale,
370
- expiresAt: expiresAt || 0,
371
- } as {
372
- data: DenormalizeNullable<E['schema']>;
373
- expiryStatus: ExpiryStatus;
374
- expiresAt: number;
375
- };
376
- }
377
-
378
- // Warn users with bad configurations
379
- /* istanbul ignore next */
380
- if (process.env.NODE_ENV !== 'production' && schema && isEntity(schema)) {
381
- if (Array.isArray(results)) {
382
- throw new Error(
383
- `fetch key ${key} has list results when single result is expected`,
384
- );
385
- }
386
- if (typeof results === 'object') {
387
- throw new Error(
388
- `fetch key ${key} has object results when entity's primary key (string) result is expected`,
389
- );
390
- }
391
- }
392
-
393
- if (!this.globalCache.results[key])
394
- this.globalCache.results[key] = new WeakEntityMap();
395
-
396
- // second argument is false if any entities are missing
397
- // eslint-disable-next-line prefer-const
398
- const { data, paths } = denormalizeCached(
399
- results,
400
- schema,
401
- state.entities,
402
- this.globalCache.entities,
403
- this.globalCache.results[key],
404
- args,
405
- ) as { data: DenormalizeNullable<E['schema']>; paths: Path[] };
406
- const invalidDenormalize = typeof data === 'symbol';
407
-
408
- // fallback to entity expiry time
409
- if (!expiresAt) {
410
- expiresAt = entityExpiresAt(paths, state.entityMeta);
411
- }
412
-
413
- // https://resthooks.io/docs/concepts/expiry-policy#expiry-status
414
- // we don't track the difference between stale or fresh because that is tied to triggering
415
- // conditions
416
- const expiryStatus =
417
- meta?.invalidated || (invalidDenormalize && !meta?.error)
418
- ? ExpiryStatus.Invalid
419
- : invalidDenormalize || endpoint.invalidIfStale || invalidResults
420
- ? ExpiryStatus.InvalidIfStale
421
- : ExpiryStatus.Valid;
422
-
423
- return { data, expiryStatus, expiresAt };
424
- };
425
- }
426
-
427
- // benchmark: https://www.measurethat.net/Benchmarks/Show/24691/0/min-reducer-vs-imperative-with-paths
428
- // earliest expiry dictates age
429
- function entityExpiresAt(
430
- paths: Path[],
431
- entityMeta: {
432
- readonly [entityKey: string]: {
433
- readonly [pk: string]: {
434
- readonly date: number;
435
- readonly expiresAt: number;
436
- readonly fetchedAt: number; // This is only the value until it is set by the CacheProvider
437
- };
438
- };
439
- },
440
- ) {
441
- let expiresAt = Infinity;
442
- for (const { pk, key } of paths) {
443
- const entityExpiry = entityMeta[key]?.[pk]?.expiresAt;
444
- // expiresAt will always resolve to false with any comparison
445
- if (entityExpiry < expiresAt) expiresAt = entityExpiry;
446
- }
447
- return expiresAt;
448
- }
449
-
450
- /** Determine whether the schema has any entities.
451
- *
452
- * Without entities, denormalization is not needed, and results should not be inferred.
453
- */
454
- function schemaHasEntity(schema: Schema): boolean {
455
- if (isEntity(schema)) return true;
456
- if (Array.isArray(schema))
457
- return schema.length !== 0 && schemaHasEntity(schema[0]);
458
- if (schema && (typeof schema === 'object' || typeof schema === 'function')) {
459
- const nestedSchema =
460
- 'schema' in schema ? (schema.schema as Record<string, Schema>) : schema;
461
- if (typeof nestedSchema === 'function') {
462
- return schemaHasEntity(nestedSchema);
463
- }
464
- return Object.values(nestedSchema).some(x => schemaHasEntity(x));
465
- }
466
- return false;
467
- }
468
-
469
- export type { ErrorTypes };
470
-
471
- class Snapshot<T = unknown> implements SnapshotInterface {
472
- private state: State<T>;
473
- private controller: Controller;
474
- readonly fetchedAt: number;
475
-
476
- constructor(controller: Controller, state: State<T>, fetchedAt = 0) {
477
- this.state = state;
478
- this.controller = controller;
479
- this.fetchedAt = fetchedAt;
480
- }
481
-
482
- /*************** Data Access ***************/
483
- /** @see https://resthooks.io/docs/api/Snapshot#getResponse */
484
- getResponse = <
485
- E extends Pick<EndpointInterface, 'key' | 'schema' | 'invalidIfStale'>,
486
- Args extends readonly [...Parameters<E['key']>],
487
- >(
488
- endpoint: E,
489
- ...args: Args
490
- ): {
491
- data: DenormalizeNullable<E['schema']>;
492
- expiryStatus: ExpiryStatus;
493
- expiresAt: number;
494
- } => {
495
- return this.controller.getResponse(endpoint, ...args, this.state);
496
- };
497
-
498
- /** @see https://resthooks.io/docs/api/Snapshot#getError */
499
- getError = <
500
- E extends Pick<EndpointInterface, 'key'>,
501
- Args extends readonly [...Parameters<E['key']>],
502
- >(
503
- endpoint: E,
504
- ...args: Args
505
- ): ErrorTypes | undefined => {
506
- return this.controller.getError(endpoint, ...args, this.state);
507
- };
508
- }
@@ -1,14 +0,0 @@
1
- export type {
2
- FetchShape,
3
- ReadShape,
4
- MutateShape,
5
- DeleteShape,
6
- } from './shapes.js';
7
- export type {
8
- SetShapeParams,
9
- ParamsFromShape,
10
- OptimisticUpdateParams,
11
- SchemaFromShape,
12
- BodyFromShape,
13
- ReturnFromShape,
14
- } from './types.js';
@@ -1,53 +0,0 @@
1
- import {
2
- Schema,
3
- EndpointExtraOptions as FetchOptions,
4
- } from '@data-client/normalizr';
5
-
6
- /** Defines the shape of a network request */
7
- export interface FetchShape<
8
- S extends Schema | undefined,
9
- Params extends Readonly<object> = Readonly<object>,
10
- Body extends Readonly<object | string> | void | unknown =
11
- | Readonly<object | string>
12
- | undefined,
13
- Response = any,
14
- > {
15
- readonly type: 'read' | 'mutate' | 'delete';
16
- fetch(params: Params, body?: Body): Promise<Response>;
17
- getFetchKey(params: Params): string;
18
- readonly schema: S;
19
- readonly options?: FetchOptions;
20
- }
21
-
22
- /** To change values on the server */
23
- export interface MutateShape<
24
- S extends Schema | undefined,
25
- Params extends Readonly<object> = Readonly<object>,
26
- Body extends Readonly<object | string> | void | unknown =
27
- | Readonly<object | string>
28
- | undefined,
29
- Response extends object | string | number | boolean | null = any,
30
- > extends FetchShape<S, Params, Body, Response> {
31
- readonly type: 'mutate';
32
- fetch(params: Params, body: Body): Promise<Response>;
33
- }
34
-
35
- /** Removes entities */
36
- export interface DeleteShape<
37
- S extends Schema | undefined,
38
- Params extends Readonly<object> = Readonly<object>,
39
- Response extends object | string | number | boolean | null = any,
40
- > extends FetchShape<S, Params, undefined, Response> {
41
- readonly type: 'mutate';
42
- fetch(params: Params, ...args: any): Promise<Response>;
43
- }
44
-
45
- /** For retrieval requests */
46
- export interface ReadShape<
47
- S extends Schema | undefined,
48
- Params extends Readonly<object> = Readonly<object>,
49
- Response extends object | string | number | boolean | null = any,
50
- > extends FetchShape<S, Params, undefined, Response> {
51
- readonly type: 'read';
52
- fetch(params: Params): Promise<Response>;
53
- }
@@ -1,72 +0,0 @@
1
- import { Schema } from '@data-client/normalizr';
2
- import type { Denormalize } from '@data-client/normalizr';
3
-
4
- import { FetchShape } from './shapes.js';
5
- import { UpdateFunction } from '../types.js';
6
-
7
- export type ResultShape<RS> = RS extends { schema: infer U } ? U : never;
8
- export type SelectReturn<RS> = RS extends {
9
- select: (...args: any[]) => infer U;
10
- }
11
- ? U
12
- : never;
13
- export type AlwaysSelect<RS> = NonNullable<SelectReturn<RS>>;
14
- export type ParamArg<RS> = RS extends {
15
- getFetchKey: (params: infer U) => any;
16
- }
17
- ? U
18
- : never;
19
- export type BodyArg<RS> = RS extends {
20
- fetch: (url: any, body: infer U) => any;
21
- }
22
- ? U
23
- : never;
24
-
25
- /** Sets a FetchShape's Param type.
26
- * Useful to constrain acceptable params (second arg) in hooks like useResource().
27
- *
28
- * @param [Shape] FetchShape to act upon
29
- * @param [Params] what to set the Params to
30
- */
31
- export type SetShapeParams<
32
- Shape extends FetchShape<any, any, any>,
33
- Params extends Readonly<object>,
34
- > = {
35
- [K in keyof Shape]: Shape[K];
36
- } & (Shape['fetch'] extends (first: any, ...rest: infer Args) => infer Return
37
- ? { fetch: (first: Params, ...rest: Args) => Return }
38
- : never);
39
-
40
- /** Get the Params type for a given Shape */
41
- export type ParamsFromShape<S> = S extends {
42
- fetch: (first: infer A, ...rest: any) => any;
43
- }
44
- ? A
45
- : S extends { getFetchKey: (first: infer A, ...rest: any) => any }
46
- ? A
47
- : never;
48
-
49
- /** Get the Schema type for a given Shape */
50
- export type SchemaFromShape<
51
- F extends FetchShape<Schema | undefined, any, any>,
52
- > = F['schema'];
53
-
54
- /** Get the Body type for a given Shape */
55
- export type BodyFromShape<F extends FetchShape<any, any, any>> = Parameters<
56
- F['fetch']
57
- >[1];
58
-
59
- export type OptimisticUpdateParams<
60
- SourceSchema extends Schema | undefined,
61
- DestShape extends FetchShape<any, any, any>,
62
- > = [
63
- DestShape,
64
- ParamsFromShape<DestShape>,
65
- UpdateFunction<SourceSchema, SchemaFromShape<DestShape>>,
66
- ];
67
-
68
- export type ReturnFromShape<S extends FetchShape<any, any, any>> = ReturnType<
69
- S['fetch']
70
- > extends unknown
71
- ? Promise<Denormalize<S['schema']>>
72
- : ReturnType<S['fetch']>;