resourcerer 1.2.3 → 2.0.0-beta-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 (59) hide show
  1. package/README.md +133 -164
  2. package/build/index.d.ts +9 -0
  3. package/build/index.js +9 -0
  4. package/build/lib/collection.d.ts +107 -0
  5. package/build/lib/collection.js +251 -0
  6. package/build/lib/config.d.ts +20 -0
  7. package/build/lib/config.js +23 -0
  8. package/build/lib/error-boundary.d.ts +12 -0
  9. package/build/lib/error-boundary.js +18 -0
  10. package/build/lib/events.d.ts +11 -0
  11. package/build/lib/events.js +12 -0
  12. package/build/lib/model-cache.d.ts +13 -0
  13. package/build/lib/model-cache.js +62 -0
  14. package/build/lib/model.d.ts +48 -0
  15. package/build/lib/model.js +170 -0
  16. package/build/lib/prefetch.d.ts +3 -0
  17. package/build/lib/prefetch.js +27 -0
  18. package/build/lib/request.d.ts +20 -0
  19. package/build/lib/request.js +53 -0
  20. package/build/lib/resourcerer.d.ts +13 -0
  21. package/build/lib/resourcerer.js +406 -0
  22. package/build/lib/sync.d.ts +18 -0
  23. package/build/lib/sync.js +58 -0
  24. package/build/lib/types.d.ts +66 -0
  25. package/build/lib/types.js +1 -0
  26. package/build/lib/utils.d.ts +14 -0
  27. package/build/lib/utils.js +87 -0
  28. package/docs/advanced_topics.md +9 -77
  29. package/docs/collection.md +28 -28
  30. package/docs/migrating_to_2.0.md +72 -0
  31. package/docs/model.md +21 -21
  32. package/docs/typescript.md +72 -22
  33. package/package.json +27 -30
  34. package/resourcerer.d.ts +58 -0
  35. package/test/collection.test.js +305 -316
  36. package/test/config.test.js +21 -75
  37. package/test/events.test.js +42 -41
  38. package/test/model-cache.test.js +99 -77
  39. package/test/model.test.js +204 -209
  40. package/test/prefetch.test.js +35 -61
  41. package/test/request.test.js +104 -109
  42. package/test/sync.test.js +122 -109
  43. package/test/utils.test.js +173 -159
  44. package/index.d.ts +0 -270
  45. package/index.js +0 -14
  46. package/lib/collection.js +0 -584
  47. package/lib/config.js +0 -131
  48. package/lib/constants.js +0 -6
  49. package/lib/error-boundary.js +0 -47
  50. package/lib/events.js +0 -19
  51. package/lib/model-cache.js +0 -131
  52. package/lib/model.js +0 -372
  53. package/lib/prefetch.js +0 -59
  54. package/lib/request.js +0 -126
  55. package/lib/resourcerer.js +0 -985
  56. package/lib/sync.js +0 -111
  57. package/lib/utils.js +0 -220
  58. package/test/model-mocks.js +0 -110
  59. package/test/setup.js +0 -63
@@ -0,0 +1,406 @@
1
+ import { hasErrored, hasLoaded, isLoading, pick } from "./utils.js";
2
+ import { ModelMap, ResourcesConfig } from "./config.js";
3
+ import React, { useEffect, useReducer, useRef, useState, } from "react";
4
+ import Collection from "./collection.js";
5
+ import ErrorBoundary from "./error-boundary.js";
6
+ import Model from "./model.js";
7
+ import ModelCache from "./model-cache.js";
8
+ import ReactDOM from "react-dom";
9
+ import request from "./request.js";
10
+ export function useResources(getResources, _props) {
11
+ const [resourceState, setResourceState] = useState({});
12
+ const props = { ..._props, ...resourceState };
13
+ const resources = generateResources(getResources, props);
14
+ const initialLoadingStates = buildResourcesLoadingState(resources.filter(withoutPrefetch), props);
15
+ const [{ loadingStates, requestStatuses, hasInitiallyLoaded }, loaderDispatch] = useReducer(loaderReducer, {
16
+ loadingStates: initialLoadingStates,
17
+ requestStatuses: {},
18
+ hasInitiallyLoaded: hasLoaded(getCriticalLoadingStates(initialLoadingStates, resources)),
19
+ });
20
+ const criticalLoadingStates = getCriticalLoadingStates(loadingStates, resources);
21
+ const [models, setModels] = useState(modelAggregator(resources.filter(withoutPrefetch)));
22
+ const isMountedRef = useIsMounted();
23
+ const componentRef = useRef({});
24
+ const prevPropsRef = useRef();
25
+ const currentPropsRef = useRef(props);
26
+ const listenedModelsRef = useRef([]);
27
+ const cachedModelsSinceLastEffect = useRef({});
28
+ const refetchedModelsSinceLastEffect = useRef({});
29
+ const forceUpdate = useForceUpdate();
30
+ const getResourcesToUpdate = () => resources
31
+ .filter(hasAllDependencies)
32
+ .filter(not(shouldBypassFetch.bind(null, props)))
33
+ .filter(([name, config]) => {
34
+ const prevConfig = prevPropsRef.current && findConfig([name, config], getResources, prevPropsRef.current);
35
+ const previousCacheKey = prevConfig && getCacheKey(prevConfig);
36
+ return (!previousCacheKey ||
37
+ previousCacheKey !== getCacheKey(config) ||
38
+ !hasAllDependencies(["", prevConfig]) ||
39
+ (config.refetch &&
40
+ (hasLoaded(loadingStates[getResourceState(name)]) ||
41
+ refetchedModelsSinceLastEffect.current[name])) ||
42
+ prevConfig?.lazy !== config.lazy);
43
+ });
44
+ const attachModelListeners = () => {
45
+ let listenedModels = resources
46
+ .map(([, config]) => getModelFromCache(config))
47
+ .filter(Boolean);
48
+ listenedModelsRef.current.forEach((model) => model.offUpdate(componentRef.current));
49
+ listenedModels.forEach((model) => model.onUpdate(forceUpdate, componentRef.current));
50
+ listenedModelsRef.current = listenedModels;
51
+ };
52
+ const pendingResources = resources
53
+ .filter(not(hasAllDependencies))
54
+ .filter(([name, config]) => prevPropsRef.current &&
55
+ hasAllDependencies(["", findConfig([name, config], getResources, prevPropsRef.current)]));
56
+ const resourcesToUpdate = getResourcesToUpdate();
57
+ const nextLoadingStates = {
58
+ ...buildResourcesLoadingState(pendingResources, props, "pending"),
59
+ ...buildResourcesLoadingState(resourcesToUpdate.filter(withoutPrefetch).filter(withoutForced), props),
60
+ };
61
+ const [loadedResources, resourcesToFetch] = partitionResources(resourcesToUpdate, nextLoadingStates);
62
+ const cachedResources = pendingResources
63
+ .concat(loadedResources)
64
+ .filter(([name]) => !cachedModelsSinceLastEffect.current[name]);
65
+ if (cachedResources.length) {
66
+ setModels(modelAggregator(cachedResources));
67
+ cachedResources.forEach(([name, config]) => {
68
+ cachedModelsSinceLastEffect.current[name] = true;
69
+ });
70
+ loadedResources.forEach(([, config]) => {
71
+ const cacheKey = getCacheKey(config);
72
+ const model = ModelCache.get(cacheKey);
73
+ ModelCache.register(cacheKey, componentRef.current);
74
+ if (model) {
75
+ provideProps(model, config.provides, props, setResourceState);
76
+ }
77
+ });
78
+ attachModelListeners();
79
+ }
80
+ resourcesToFetch.forEach(([name, config]) => {
81
+ if (config.refetch) {
82
+ refetchedModelsSinceLastEffect.current[name] = true;
83
+ }
84
+ });
85
+ if (Object.keys(nextLoadingStates).some((ky) => nextLoadingStates[ky] !== loadingStates[ky])) {
86
+ loaderDispatch({ type: "loading", payload: nextLoadingStates });
87
+ }
88
+ useEffect(() => {
89
+ if (resourcesToUpdate.length) {
90
+ if (prevPropsRef.current) {
91
+ resourcesToUpdate.forEach(([name, config]) => {
92
+ const prevConfig = findConfig([name, config], getResources, prevPropsRef.current), prevCacheKey = getCacheKey(prevConfig);
93
+ const prevModel = ModelCache.get(prevCacheKey);
94
+ ModelCache.unregister(componentRef.current, prevCacheKey);
95
+ if (prevModel && prevConfig.data && !prevConfig.data?.id && config.data?.id) {
96
+ ModelCache.put(getCacheKey(config), prevModel);
97
+ ModelCache.remove(prevCacheKey);
98
+ }
99
+ });
100
+ }
101
+ fetchResources(resourcesToFetch, props, {
102
+ component: componentRef.current,
103
+ isCurrentResource: ([name, config], cacheKey) => isMountedRef.current &&
104
+ !config.prefetch &&
105
+ cacheKey === findCacheKey([name, config], getResources, currentPropsRef.current),
106
+ setResourceState,
107
+ onRequestSuccess: (model, status, [name, config]) => {
108
+ ReactDOM.unstable_batchedUpdates(() => {
109
+ setModels(modelAggregator([[name, config]]));
110
+ loaderDispatch({
111
+ type: "loaded",
112
+ payload: { name, status, resources },
113
+ });
114
+ });
115
+ },
116
+ onRequestFailure: (status, [name, config]) => {
117
+ ReactDOM.unstable_batchedUpdates(() => {
118
+ setModels(modelAggregator([[name, config]]));
119
+ loaderDispatch({
120
+ type: "error",
121
+ payload: { name, status },
122
+ });
123
+ });
124
+ },
125
+ }).then(() => {
126
+ if (isMountedRef.current) {
127
+ attachModelListeners();
128
+ }
129
+ });
130
+ }
131
+ prevPropsRef.current = props;
132
+ cachedModelsSinceLastEffect.current = {};
133
+ refetchedModelsSinceLastEffect.current = {};
134
+ });
135
+ useEffect(() => {
136
+ const bypassedModels = resources
137
+ .filter(shouldBypassFetch.bind(null, props))
138
+ .map(([name, { resourceKey }]) => props[getResourcePropertyName(name, resourceKey)])
139
+ .filter(Boolean);
140
+ bypassedModels.forEach((model) => model.onUpdate(forceUpdate, componentRef.current));
141
+ return () => {
142
+ ModelCache.unregister(componentRef.current);
143
+ resources
144
+ .map(([, config]) => getModelFromCache(config))
145
+ .filter(Boolean)
146
+ .concat(bypassedModels)
147
+ .forEach((model) => model?.offUpdate(componentRef.current));
148
+ };
149
+ }, []);
150
+ currentPropsRef.current = props;
151
+ return {
152
+ ...models,
153
+ ...resourceState,
154
+ ...pick(props, ...Object.keys(models)),
155
+ refetch: (keys) => {
156
+ ReactDOM.unstable_batchedUpdates(() => {
157
+ keys = Array.isArray(keys) ? keys : [keys];
158
+ keys.forEach((name) => {
159
+ const model = getModelFromCache(findConfig([name, {}], getResources, props));
160
+ if (model) {
161
+ model.refetching = true;
162
+ model.triggerUpdate();
163
+ }
164
+ });
165
+ });
166
+ },
167
+ invalidate: (keys) => (Array.isArray(keys) ? keys : [keys]).forEach((key) => ModelCache.removeAllWithModel(key)),
168
+ setResourceState,
169
+ ...loadingStates,
170
+ ...requestStatuses,
171
+ hasErrored: hasErrored(criticalLoadingStates),
172
+ hasLoaded: hasLoaded(criticalLoadingStates),
173
+ isLoading: isLoading(criticalLoadingStates),
174
+ hasInitiallyLoaded,
175
+ };
176
+ }
177
+ export const withResources = (getResources) => (Component) => function DataCarrier(props) {
178
+ const resources = useResources(getResources, props);
179
+ return React.createElement(ErrorBoundary, {
180
+ children: React.createElement(Component, {
181
+ ...props,
182
+ ...resources,
183
+ }),
184
+ });
185
+ };
186
+ function generateResources(getResources, props) {
187
+ return Object.entries(getResources(props) || {}).reduce((memo, [name, config = {}]) => memo.concat([
188
+ [
189
+ name,
190
+ {
191
+ resourceKey: config.resourceKey || name,
192
+ refetch: !!getModelFromCache({ ...config, resourceKey: config.resourceKey || name })
193
+ ?.refetching,
194
+ ...config,
195
+ },
196
+ ],
197
+ ].concat((config.prefetches || []).map((prefetch) => [
198
+ name,
199
+ {
200
+ resourceKey: config.resourceKey || name,
201
+ ...getResources({ ...props, ...prefetch })[name],
202
+ prefetch: true,
203
+ },
204
+ ]))), []);
205
+ }
206
+ function getResourceState(name) {
207
+ return `${name}LoadingState`;
208
+ }
209
+ function getResourceStatus(name) {
210
+ return `${name}Status`;
211
+ }
212
+ function getResourcePropertyName(baseName, resourceKey) {
213
+ const Constructor = ModelMap[resourceKey];
214
+ return Constructor?.prototype instanceof Collection ?
215
+ `${baseName}Collection`
216
+ : `${baseName}Model`;
217
+ }
218
+ function getEmptyModel({ resourceKey, data, options, path }) {
219
+ const Model_ = typeof ModelMap[resourceKey] === "function" ? ModelMap[resourceKey] : Model;
220
+ const emptyInstance = new Model_(data, { ...options, ...path });
221
+ emptyInstance.isEmptyModel = true;
222
+ Object.freeze(emptyInstance.attributes);
223
+ Object.freeze(emptyInstance.models);
224
+ return emptyInstance;
225
+ }
226
+ export function getCacheKey({ resourceKey, params = {}, path = {}, data = {}, }) {
227
+ const Constructor = ModelMap[resourceKey];
228
+ const toKeyValString = ([key, val]) => (val ? `${key}=${val}` : ""), fields = (Constructor?.dependencies || [])
229
+ .map((key) => typeof key === "function" ?
230
+ Object.entries(key(params)).map(toKeyValString).join("_")
231
+ : toKeyValString([key, path[key] || data[key] || params[key]]))
232
+ .filter(Boolean);
233
+ return `${resourceKey || ""}${fields.length ? `~${fields.sort().join("_")}` : ""}`;
234
+ }
235
+ function findConfig([name, { prefetch }], getResources, props) {
236
+ const [, config = { resourceKey: "" }] = generateResources(getResources, props).find(([_name, _config = {}]) => name === _name &&
237
+ JSON.stringify(_config.prefetch) === JSON.stringify(prefetch)) || [];
238
+ return config;
239
+ }
240
+ function findCacheKey(resource, getResources, props) {
241
+ return getCacheKey(findConfig(resource, getResources, props)) || "";
242
+ }
243
+ function buildResourcesLoadingState(resources, props, defaultState = "loaded") {
244
+ return resources.reduce((state, [name, config]) => Object.assign(state, {
245
+ [getResourceState(name)]: (!config.refetch &&
246
+ !config.force &&
247
+ (shouldBypassFetch(props, [name, config]) ||
248
+ (getModelFromCache(config) && !getModelFromCache(config)?.lazy))) ?
249
+ defaultState
250
+ : !hasAllDependencies(["", config]) ? "pending"
251
+ : config.lazy ?
252
+ "loaded"
253
+ : "loading",
254
+ }), {});
255
+ }
256
+ function hasAllDependencies([, config]) {
257
+ return !("dependsOn" in config) || !!config.dependsOn;
258
+ }
259
+ function getModelFromCache(...args) {
260
+ return ModelCache.get(getCacheKey(...args));
261
+ }
262
+ function withoutPrefetch([, config]) {
263
+ return !config.prefetch;
264
+ }
265
+ function withoutNoncritical([, config]) {
266
+ return !config.noncritical;
267
+ }
268
+ function withoutForced([, config]) {
269
+ return !config.force;
270
+ }
271
+ function shouldBypassFetch(props, [name, { resourceKey }]) {
272
+ return !!(getResourcePropertyName(name, resourceKey) in props);
273
+ }
274
+ function not(fn) {
275
+ return (...args) => !fn(...args);
276
+ }
277
+ function useForceUpdate() {
278
+ const [, forceUpdate] = useState({});
279
+ return () => forceUpdate({});
280
+ }
281
+ function useIsMounted() {
282
+ const isMountedRef = useRef(false);
283
+ useEffect(() => {
284
+ isMountedRef.current = true;
285
+ return () => {
286
+ isMountedRef.current = false;
287
+ };
288
+ }, []);
289
+ return isMountedRef;
290
+ }
291
+ function trackRequestTime(name, { params, path } = {}) {
292
+ const measurementName = `${name}Fetch`;
293
+ let fetchEntry;
294
+ if (window.performance.getEntriesByName(name).length) {
295
+ window.performance.measure(measurementName, name);
296
+ fetchEntry = window.performance.getEntriesByName(measurementName).pop();
297
+ ResourcesConfig.track("API Fetch", {
298
+ Resource: name,
299
+ params,
300
+ path,
301
+ duration: Math.round(fetchEntry?.duration || 0),
302
+ });
303
+ window.performance.clearMarks(name);
304
+ window.performance.clearMeasures(measurementName);
305
+ }
306
+ }
307
+ function getCriticalLoadingStates(loadingStates, resources) {
308
+ return resources
309
+ .filter(withoutNoncritical)
310
+ .filter(withoutPrefetch)
311
+ .map(([name]) => loadingStates[getResourceState(name)])
312
+ .filter((x) => x);
313
+ }
314
+ function modelAggregator(resources) {
315
+ const newModels = resources.reduce((memo, [name, config]) => Object.assign(memo, {
316
+ [getResourcePropertyName(name, config.resourceKey)]: getModelFromCache(config) || getEmptyModel(config),
317
+ }), {});
318
+ return (models = {}) => (Object.keys(newModels).filter((key) => models[key] !== newModels[key]).length) ?
319
+ { ...models, ...newModels }
320
+ : models;
321
+ }
322
+ function partitionResources(resourcesToUpdate, loadingStates) {
323
+ return resourcesToUpdate.reduce((memo, [name, config]) => (config.refetch ||
324
+ config.force ||
325
+ config.prefetch ||
326
+ !hasLoaded(loadingStates[getResourceState(name)]) ||
327
+ getModelFromCache(config)?.lazy) ?
328
+ [memo[0], memo[1].concat([[name, config]])]
329
+ : [memo[0].concat([[name, config]]), memo[1]], [[], []]);
330
+ }
331
+ function loaderReducer({ loadingStates, requestStatuses, hasInitiallyLoaded }, { type, payload = {} }) {
332
+ switch (type) {
333
+ case "error":
334
+ case "loaded": {
335
+ const { name, status, resources } = payload;
336
+ let nextLoadingStates = { ...loadingStates, [getResourceState(name)]: type };
337
+ return {
338
+ loadingStates: nextLoadingStates,
339
+ requestStatuses: {
340
+ ...requestStatuses,
341
+ ...(status ? { [getResourceStatus(name)]: status } : {}),
342
+ },
343
+ hasInitiallyLoaded: hasInitiallyLoaded ||
344
+ (type === "loaded" &&
345
+ hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources)) &&
346
+ !hasInitiallyLoaded),
347
+ };
348
+ }
349
+ case "loading":
350
+ return {
351
+ loadingStates: { ...loadingStates, ...payload },
352
+ requestStatuses,
353
+ hasInitiallyLoaded,
354
+ };
355
+ default:
356
+ return { loadingStates, requestStatuses, hasInitiallyLoaded };
357
+ }
358
+ }
359
+ function shouldMeasureRequest(resourceKey, config) {
360
+ const Constructor = ModelMap[resourceKey];
361
+ if (!Constructor || !window.performance || !window.performance.mark) {
362
+ return false;
363
+ }
364
+ return typeof Constructor.measure === "function" ?
365
+ Constructor.measure(config)
366
+ : !!Constructor.measure;
367
+ }
368
+ function fetchResources(resources, props, { component, isCurrentResource, setResourceState, onRequestSuccess, onRequestFailure, }) {
369
+ resources = resources.concat().sort((a, b) => a[1].prefetch ? 2
370
+ : b[1].prefetch ? -2
371
+ : a[1].noncritical ? 1
372
+ : b[1].noncritical ? -1
373
+ : 0);
374
+ return Promise.all(resources.map(([name, config]) => {
375
+ const { resourceKey, provides, refetch, ...rest } = config;
376
+ const cacheKey = getCacheKey(config);
377
+ const shouldMeasure = shouldMeasureRequest(resourceKey, config) && !getModelFromCache(config);
378
+ if (shouldMeasure) {
379
+ window.performance.mark(name);
380
+ }
381
+ return request(cacheKey, ModelMap[resourceKey], {
382
+ component,
383
+ force: refetch,
384
+ ...rest,
385
+ }).then(([model, status]) => {
386
+ if (shouldMeasure) {
387
+ trackRequestTime(name, config);
388
+ }
389
+ delete model.refetching;
390
+ if (isCurrentResource([name, config], cacheKey)) {
391
+ provideProps(model, provides, props, setResourceState);
392
+ onRequestSuccess(model, status, [name, config]);
393
+ }
394
+ }, (status) => {
395
+ delete getModelFromCache(config)?.refetching;
396
+ if (isCurrentResource([name, config], cacheKey)) {
397
+ onRequestFailure(status, [name, config]);
398
+ }
399
+ });
400
+ }));
401
+ }
402
+ function provideProps(model, provides, props, setResourceState) {
403
+ if (provides) {
404
+ setResourceState((state) => ({ ...state, ...provides(model, props) }));
405
+ }
406
+ }
@@ -0,0 +1,18 @@
1
+ import { ResourcererConfig } from "./config.js";
2
+ import Model from "./model.js";
3
+ import Collection from "./collection.js";
4
+ type SyncResolvedValue = [any, Response];
5
+ export type SyncOptions = {
6
+ attrs?: Record<string, any>;
7
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
8
+ params?: Record<string, any>;
9
+ url?: string;
10
+ minDuration?: number;
11
+ error?: (response: Response) => any;
12
+ headers?: Record<string, string>;
13
+ [key: string]: any;
14
+ };
15
+ export default function (model: Model | Collection, options?: SyncOptions): Promise<SyncResolvedValue>;
16
+ export declare function ajax(options: SyncOptions & Required<Pick<SyncOptions, "error" | "url" | "params">>): Promise<SyncResolvedValue>;
17
+ export declare function setRequestPrefilter(_prefilter: ResourcererConfig["prefilter"]): void;
18
+ export {};
@@ -0,0 +1,58 @@
1
+ import { result, urlError } from "./utils.js";
2
+ import { ResourcesConfig } from "./config.js";
3
+ const MIME_TYPE_JSON = "application/json";
4
+ let prefilter = (x) => x;
5
+ export default function (model, options = {}) {
6
+ return ajax({
7
+ contentType: MIME_TYPE_JSON,
8
+ params: options.params || ["POST", "PATCH", "PUT"].includes(options.method || "") ?
9
+ options.attrs || model.toJSON()
10
+ : {},
11
+ url: options.url || result(model, "url", model.urlOptions) || urlError(),
12
+ error: (response) => response,
13
+ ...options,
14
+ });
15
+ }
16
+ export function ajax(options) {
17
+ const hasParams = !!Object.keys(options.params).length;
18
+ const hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method || "") && hasParams;
19
+ const startTime = Date.now();
20
+ const onRequestComplete = (json, response) => {
21
+ const requestDuration = Date.now() - startTime;
22
+ const routeRequest = (resolve, reject) => response.ok ?
23
+ resolve([json, response])
24
+ : reject(options.error(Object.assign(response, { json })));
25
+ return new Promise((resolve, reject) => !options.minDuration || requestDuration >= options.minDuration ?
26
+ routeRequest(resolve, reject)
27
+ : window.setTimeout(() => routeRequest(resolve, reject), options.minDuration - requestDuration));
28
+ };
29
+ if (options.method === "GET" && hasParams) {
30
+ options.url +=
31
+ (options.url.indexOf("?") > -1 ? "&" : "?") +
32
+ ResourcesConfig.stringify(options.params, options);
33
+ }
34
+ options = { ...options, ...prefilter(options) };
35
+ return window
36
+ .fetch(options.url, {
37
+ ...options,
38
+ headers: {
39
+ Accept: MIME_TYPE_JSON,
40
+ ...(hasBodyContent ? { "Content-Type": options.contentType } : {}),
41
+ ...options.headers,
42
+ },
43
+ ...(hasBodyContent ?
44
+ {
45
+ body: typeof options.params === "string" ? options.params
46
+ : options.contentType === MIME_TYPE_JSON ? JSON.stringify(options.params)
47
+ : ResourcesConfig.stringify(options.params, options),
48
+ }
49
+ : {}),
50
+ })
51
+ .then((res) => res
52
+ .json()
53
+ .catch(() => ({}))
54
+ .then((json) => onRequestComplete(json, res)));
55
+ }
56
+ export function setRequestPrefilter(_prefilter) {
57
+ prefilter = _prefilter;
58
+ }
@@ -0,0 +1,66 @@
1
+ import Model from "./model.js";
2
+ import Collection from "./collection.js";
3
+ export type LoadingStates = "error" | "loading" | "loaded" | "pending";
4
+ export type Resource = [string, InternalResourceConfigObj];
5
+ export type Props = Record<string, any>;
6
+ export interface ModelMap {
7
+ [key: string]: new (...args: any[]) => any;
8
+ }
9
+ export type ResourceKeys = Extract<keyof ModelMap, string>;
10
+ export type LoadingStateKey = `${string}LoadingState`;
11
+ export type LoadingStateObj = {
12
+ [key: LoadingStateKey]: LoadingStates;
13
+ };
14
+ export type WithModelSuffix<K extends string, C> = C extends Collection<any, any> ? `${K}Collection` : `${K}Model`;
15
+ export type ResourceConfigObj = {
16
+ data?: {
17
+ [key: string]: any;
18
+ };
19
+ dependsOn?: boolean;
20
+ force?: boolean;
21
+ lazy?: boolean;
22
+ resourceKey?: ResourceKeys;
23
+ noncritical?: boolean;
24
+ options?: {
25
+ [key: string]: any;
26
+ };
27
+ path?: {
28
+ [key: string]: any;
29
+ };
30
+ params?: {
31
+ [key: string]: any;
32
+ };
33
+ prefetches?: {
34
+ [key: string]: any;
35
+ }[];
36
+ provides?: (model: Model | Collection, props: Record<string, any>) => {
37
+ [key: string]: any;
38
+ };
39
+ };
40
+ export type InternalResourceConfigObj = ResourceConfigObj & {
41
+ resourceKey: ResourceKeys;
42
+ prefetch?: boolean;
43
+ refetch?: boolean;
44
+ };
45
+ export type ExecutorFunction<T extends ResourceKeys = ResourceKeys, O extends {
46
+ [key: string]: any;
47
+ } = any> = (props: O) => {
48
+ [Key in T]?: Key extends ResourceKeys ? ResourceConfigObj : ResourceConfigObj & {
49
+ resourceKey: T;
50
+ };
51
+ };
52
+ export type UseResourcesResponse = {
53
+ isLoading: boolean;
54
+ hasErrored: boolean;
55
+ hasLoaded: boolean;
56
+ hasInitiallyLoaded: boolean;
57
+ refetch: (keys: ResourceKeys[]) => void;
58
+ invalidate: (keys: ResourceKeys[]) => void;
59
+ setResourceState(newState: {
60
+ [key: string]: any;
61
+ }): void;
62
+ [key: `${string}LoadingState`]: LoadingStates;
63
+ [key: `${string}Collection`]: Collection;
64
+ [key: `${string}Model`]: Model;
65
+ [key: `${string}Status`]: number;
66
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import type { LoadingStates } from "./types.js";
2
+ export declare const hasErrored: (loadingStates: LoadingStates | LoadingStates[]) => boolean;
3
+ export declare const isLoading: (loadingStates: LoadingStates | LoadingStates[]) => boolean;
4
+ export declare const hasLoaded: (loadingStates: LoadingStates | LoadingStates[]) => boolean;
5
+ export declare const isPending: (loadingStates: LoadingStates | LoadingStates[]) => boolean;
6
+ export declare function noOp(): void;
7
+ export declare function once(fn: (...args: any[]) => void): (...args: any[]) => void;
8
+ export declare function pick<T, K extends keyof T>(obj?: T, ...keys: K[]): { [P in K]: T[P]; };
9
+ export declare function omit<T extends Record<string, any>, K extends keyof T>(obj?: T, ...keys: K[]): { [P in K]: T[P]; };
10
+ export declare const uniqueId: (prefix?: string) => string;
11
+ export declare function urlError(): void;
12
+ export declare function isDeepEqual(obj1: Record<string, any>, obj2: Record<string, any>): boolean;
13
+ export declare function sortBy(list: any[] | undefined, comparator: (val: any) => string | number): any[];
14
+ export declare function result(obj: Record<string, any> | undefined, prop: string, ...args: any[]): any;
@@ -0,0 +1,87 @@
1
+ export const hasErrored = (loadingStates) => qualifyLoadingStates(loadingStates).some((state) => state === "error");
2
+ export const isLoading = (loadingStates) => qualifyLoadingStates(loadingStates).some((state) => state === "loading");
3
+ export const hasLoaded = (loadingStates) => qualifyLoadingStates(loadingStates).every((state) => state === "loaded");
4
+ export const isPending = (loadingStates) => qualifyLoadingStates(loadingStates).some((state) => state === "pending");
5
+ export function noOp() { }
6
+ export function once(fn) {
7
+ let invoked = false;
8
+ return (...args) => {
9
+ if (!invoked) {
10
+ fn.call(null, ...args);
11
+ invoked = true;
12
+ }
13
+ };
14
+ }
15
+ export function pick(obj = {}, ...keys) {
16
+ return keys.reduce((memo, key) => {
17
+ if (obj[key]) {
18
+ memo[key] = obj[key];
19
+ }
20
+ return memo;
21
+ }, {});
22
+ }
23
+ export function omit(obj = {}, ...keys) {
24
+ return pick(obj, ...Object.keys(obj).filter((key) => !keys.includes(key)));
25
+ }
26
+ function qualifyLoadingStates(loadingStates) {
27
+ if (!Array.isArray(loadingStates)) {
28
+ return [loadingStates];
29
+ }
30
+ return loadingStates;
31
+ }
32
+ export const uniqueId = (() => {
33
+ let count = 0;
34
+ return (prefix = "") => {
35
+ count++;
36
+ return `${prefix}${count}`;
37
+ };
38
+ })();
39
+ export function urlError() {
40
+ throw new Error('A "url" property or function must be specified');
41
+ }
42
+ export function isDeepEqual(obj1, obj2) {
43
+ if (obj1 === obj2) {
44
+ return true;
45
+ }
46
+ else if (typeof obj1 === "object" &&
47
+ obj1 !== null &&
48
+ typeof obj2 === "object" &&
49
+ obj2 !== null) {
50
+ if (Object.keys(obj1).length !== Object.keys(obj2).length) {
51
+ return false;
52
+ }
53
+ for (let prop in obj1) {
54
+ if (prop in obj2) {
55
+ if (!isDeepEqual(obj1[prop], obj2[prop])) {
56
+ return false;
57
+ }
58
+ }
59
+ else {
60
+ return false;
61
+ }
62
+ }
63
+ return true;
64
+ }
65
+ return false;
66
+ }
67
+ export function sortBy(list = [], comparator) {
68
+ return list
69
+ .map((value, index) => ({ value, index, criteria: comparator(value) }))
70
+ .sort((left, right) => {
71
+ const a = left.criteria;
72
+ const b = right.criteria;
73
+ if (a !== b) {
74
+ if (a > b || a === undefined) {
75
+ return 1;
76
+ }
77
+ else if (a < b || b === undefined) {
78
+ return -1;
79
+ }
80
+ }
81
+ return left.index - right.index;
82
+ })
83
+ .map(({ value }) => value);
84
+ }
85
+ export function result(obj = {}, prop, ...args) {
86
+ return typeof obj[prop] === "function" ? obj[prop](...args) : obj[prop];
87
+ }