resourcerer 2.3.0 → 2.3.2

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.
package/CONTRIBUTING.md CHANGED
@@ -2,36 +2,44 @@
2
2
 
3
3
  Please use the following guidelines when contributing to this repository:
4
4
 
5
- * Use github issues to report bugs and feature requests. For help debugging, please use StackOverflow.
5
+ * Use GitHub issues to report bugs and feature requests. For help debugging, please use StackOverflow.
6
6
 
7
- * Pull requests should be made to master. Before sending one for a feature or bug fix, be sure to add [tests](#tests). Don't bother with documentation; we'll add it before we release.
7
+ * Pull requests should be made to `main`. Before sending one for a feature or bug fix, be sure to add [tests](#tests). Please update documentation when your change affects the public API or documented behavior.
8
8
 
9
9
  * Use the same coding style as the rest of the codebase; besides passing tests, all changes must also pass style checks.
10
10
 
11
11
 
12
12
  ## Conduct
13
- See our [Code of Conduct](https://github.com/SiftScience/resourcerer/CODE_OF_CONDUCT.md) page.
13
+ See our [Code of Conduct](https://github.com/noahgrant/resourcerer/CODE_OF_CONDUCT.md) page.
14
14
 
15
15
 
16
16
  ## Clone the repo
17
17
  To get started in development, clone the repository and install dependencies:
18
-
18
+
19
19
  ```sh
20
- $ git clone git@github.com:SiftScience/resourcerer.git
20
+ $ git clone git@github.com:noahgrant/resourcerer.git
21
21
  $ cd resourcerer
22
22
  $ npm i
23
23
  ```
24
24
 
25
25
 
26
26
  ## Tests
27
- There is a webpack and babel build for testing purposes via karma, and can be triggered with:
27
+ Tests run with [Vitest](https://vitest.dev/). Trigger them with:
28
28
 
29
29
  `$ npm test`
30
30
 
31
- This will build and transpile the files, and then run the tests. You can run the linter with:
31
+ You can run the TypeScript typechecker with:
32
+
33
+ `$ npm run typecheck`
34
+
35
+ You can run the linter with:
32
36
 
33
37
  `$ npm run lint`
34
38
 
35
- To run both at once, you can run:
39
+ To run typecheck, tests, and lint together:
36
40
 
37
41
  `$ npm run checks`
42
+
43
+ For a watch mode during development:
44
+
45
+ `$ npm run test:watch`
package/README.md CHANGED
@@ -21,7 +21,7 @@ Additional features include:
21
21
  * forced cache invalidation
22
22
  * updating a component when a resource updates
23
23
  * zero dependencies
24
- * < 6kB!
24
+ * under 10kB gzipped!
25
25
 
26
26
  Getting started is easy:
27
27
 
@@ -136,7 +136,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
136
136
  1. [Changing Props](#changing-props)
137
137
  1. [Common Resource Config Options](#common-resource-config-options)
138
138
  1. [params](#params)
139
- 1. [options](#options)
139
+ 1. [path](#path)
140
140
  1. [noncritical](#noncritical)
141
141
  1. [force](#force)
142
142
  1. [Custom Resource Names](#custom-resource-names)
@@ -144,19 +144,20 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
144
144
  1. [data](#data)
145
145
  1. [lazy](#lazy)
146
146
  1. [minDuration](#minduration)
147
+ 1. [fetch](#fetch)
147
148
  1. [dependsOn](#dependson)
148
149
  1. [provides](#provides)
149
150
  1. [Data mutations](#data-mutations)
150
151
  1. [Serial Requests](#serial-requests)
151
- 2. [Canonical Models](#canonical-models)
152
- 3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
153
- 4. [Using resourcerer with TypeScript](docs/typescript.md)
154
- 4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
155
- 5. [Declarative Cache Keys](#declarative-cache-keys)
156
- 6. [Prefetch on Hover](#prefetch-on-hover)
157
- 7. [Refetching](#refetching)
158
- 8. [Cache Invalidation](#cache-invalidation)
159
- 9. [Tracking Request Times](#tracking-request-times)
152
+ 1. [Canonical Models](#canonical-models)
153
+ 1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
154
+ 1. [Using resourcerer with TypeScript](docs/typescript.md)
155
+ 1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
156
+ 1. [Declarative Cache Keys](#declarative-cache-keys)
157
+ 1. [Prefetch on Hover](#prefetch-on-hover)
158
+ 1. [Refetching](#refetching)
159
+ 1. [Cache Invalidation](#cache-invalidation)
160
+ 1. [Tracking Request Times](#tracking-request-times)
160
161
  1. [Configuring resourcerer](#configuring-resourcerer)
161
162
  1. [FAQs](#faqs)
162
163
  1. [Migrating to v2.0](#migrating-to-v20)
@@ -166,7 +167,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
166
167
 
167
168
  `$ npm i resourcerer` or `yarn add resourcerer`
168
169
 
169
- `resourcerer` requires on React >= 16.8 but has no external dependencies.
170
+ `resourcerer` requires React >= 16.14 (peer range includes React 17, 18, and 19) but has no external dependencies.
170
171
 
171
172
  Note: Resourcerer is written in TypeScript and is compiled to ESNext. It does no further transpiling&mdash;including `import`/`export`.
172
173
  If you are using TypeScript yourself, this won't be a problem. If you're not, and you're not babelifying (or similar) your `node_modules` folder, you'll need to make an exception for this package, ie:
@@ -256,7 +257,8 @@ Back to the executor function. In the example above, you see it returns an objec
256
257
  Of course, in our initial example, the `todosCollection` won’t be populated with data immediately since, after all, the resource has to be fetched from the API. Some of the most **significant** and most common React UI states we utilize are whether a component’s critical resources have loaded entirely, whether any are still loading, or whether any have errored out. This is how we can appropriately cover our bases&mdash;i.e., we can ensure the component shows a loader while the resource is still in route, or if something goes wrong, we can ensure the component will still fail gracefully and not break the layout. To address these concerns, the `useResources` hook/`withResources` HOC gives you several loading state helper props. From our last example:
257
258
 
258
259
 
259
- - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/06ed847a8d8d0daefd3ad1b7634d887767d338ac/lib/types.ts#L4). There will be one for each resource, and the property names will be equal to `${resourceKey}LoadingState`)
260
+ - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/main/lib/types.ts#L4). There will be one for each resource, and the property names will be equal to `${resourceKey}LoadingState`)
261
+ - `todosStatus` {number} - the HTTP status code from the most recent response for that resource (one per resource as `${resourceKey}Status`)
260
262
  - `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
261
263
  - `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
262
264
  - `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
@@ -494,7 +496,7 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
494
496
 
495
497
  - De-prioritize fetching the resource until after all critical resources have been fetched
496
498
  - Remove the resource from consideration within the component-wide loading states (`hasLoaded`, `isLoading`, `hasErrored`), giving us the ability to render without waiting on those resources
497
- - Can set our own UI logic around displaying noncritical data based on their individual loading states, ie `usersLoadingState`, which can be passed to the pure helper methods, `Utils.hasLoaded`, `Utils.hasErrored`, and `Utils.isLoading` from `resourcerer`.
499
+ - Can set our own UI logic around displaying noncritical data based on their individual loading states, ie `usersLoadingState`, which can be passed to the pure helper methods, `Utils.hasLoaded`, `Utils.hasErrored`, `Utils.isLoading`, and `Utils.isPending` from `resourcerer`.
498
500
 
499
501
 
500
502
 
@@ -520,7 +522,7 @@ This behavior is similar to the behavior you get with [cache invalidation](#cach
520
522
  Passing a `resourceKey: <ResourceKeys>` option allows you to pass a custom name as the `withResources` key, which will become the base name for component-related props passed down to the component. For example, this configuration:
521
523
 
522
524
  ```js
523
- const getResources = (props) => ({myRadTodos: {resourceKey: todos});
525
+ const getResources = (props) => ({myRadTodos: {resourceKey: 'todos'}});
524
526
 
525
527
  export default function MyComponentWithTodos {
526
528
  const {
@@ -620,7 +622,7 @@ function TodoSearch(props) {
620
622
 
621
623
  // todo_search_item.jsx
622
624
  // the todoModel is never actually fetched here, it's only listened on, allowing any changes made elsewhere in the page to be reflected here.
623
- getResources = () => ({todo: {id: props.id, lazy: true}});
625
+ getResources = () => ({todo: {data: {id: props.id, lazy: true}});
624
626
 
625
627
  function TodoSearchItem(props) {
626
628
  const {todoModel} = useResources(getResources, props);
@@ -637,7 +639,20 @@ If the todo model has been fetched already, we'll read straight from that. And i
637
639
 
638
640
  ### minDuration
639
641
 
640
- Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take. This is great for [save and destroy](#data-mutations) requests. It will work for fetch requests via `useResources`, as well, but beware: if multiple components use the same resource and there are different (or missing) values for `minDuration`, this will cause a race condition.
642
+ Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take on [save and destroy](#data-mutations) calls (for example `model.save(attrs, {minDuration: 300})`). It is not a resource config option and is not applied to fetches made through `useResources` / `withResources`.
643
+
644
+ ### fetch
645
+
646
+ Pass `fetch: false` (or any expression that evaluates to false) to instantiate and cache a model **without** calling the network. Useful when composing a new resource client-side before it has an id, or when you already have data. See [Unfetched Resources](/docs/advanced_topics.md#unfetched-resources) and [Recaching newly-saved models](/docs/advanced_topics.md#recaching-newly-saved-models).
647
+
648
+ ```js
649
+ const getResources = (props) => ({
650
+ todo: {
651
+ data: {id: props.id},
652
+ fetch: !!props.id
653
+ }
654
+ });
655
+ ```
641
656
 
642
657
  ### dependsOn
643
658
 
@@ -645,7 +660,7 @@ See the section on [serial requests](#serial-requests).
645
660
 
646
661
  ### provides
647
662
 
648
- See the section on [serial requests](#serial-requests).
663
+ See the section on [serial requests](#serial-requests). The `provides` function receives `(model, props)` and should return a map of prop names to values that get set via `setResourceState` for dependent resources.
649
664
 
650
665
  # Data Mutations
651
666
 
@@ -659,7 +674,7 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
659
674
  function MyComponent(props) {
660
675
  const {myModel} = useResources(getResources, props),
661
676
  onSave = () => myModel.save({foo: 'bar'})
662
- .then([model]) => // ...)
677
+ .then(([model]) => // ...)
663
678
  .catch(() => alert('request failed'));
664
679
 
665
680
  return <button onClick={onSave}>Persist model</button>;
@@ -1236,7 +1251,7 @@ ResourcesConfig.set(configObj);
1236
1251
 
1237
1252
  * Can `resourcerer` do anything other than `GET` requests?
1238
1253
 
1239
- `resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)). Note that this is not the same as only making `GET` requests; pass in a `method: 'POST'` property in a resource's config to turn the `params` property into a POST body, for example, when making a search request.
1254
+ `resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)), which defaults to `GET`. If a resource needs a different HTTP method (for example a search endpoint that takes a POST body), override [`fetch`](/docs/model.md#fetch) on that Model/Collection class once—do not set `method` in each resource config.
1240
1255
 
1241
1256
  For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
1242
1257
 
@@ -1,7 +1,7 @@
1
1
  import Events from "./events.js";
2
2
  import Model, { type CanonicalModelSubscription, type ConstructorOptions, type SetOptions } from "./model.js";
3
3
  import sync, { type SyncOptions } from "./sync.js";
4
- import { ResourceConfigObj } from "./types.js";
4
+ import { ResourceConfigObj, ResourceKeys } from "./types.js";
5
5
  import CanonicalModelConstructor from "./canonical-model.js";
6
6
  type CSetOptions = {
7
7
  parse?: boolean;
@@ -33,6 +33,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
33
33
  static cacheTimeout: number;
34
34
  static comparator: comparator;
35
35
  static measure: boolean | ((config: ResourceConfigObj) => boolean);
36
+ static invalidates: ResourceKeys[];
36
37
  toJSON(): T[];
37
38
  sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
38
39
  add(models: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
@@ -32,6 +32,7 @@ export default class Collection extends Events {
32
32
  static cacheTimeout;
33
33
  static comparator;
34
34
  static measure = false;
35
+ static invalidates = [];
35
36
  toJSON() {
36
37
  return this.map((model) => model.toJSON());
37
38
  }
@@ -1,9 +1,9 @@
1
- import Collection from "./collection.js";
2
- import Model from "./model.js";
1
+ import type Collection from "./collection.js";
2
+ import type Model from "./model.js";
3
3
  import { ResourceKeys } from "./types.js";
4
4
  type Component = NonNullable<unknown>;
5
5
  declare const ModelCache: {
6
- get(cacheKey: string): Collection<object, object, {
6
+ get(cacheKey: string): Model<Record<string, any>, Record<string, any>> | Collection<object, object, {
7
7
  new (attributes?: object | undefined, options?: object & import("./model.js").SetOptions & import("./model.js").ConstructorOptions): Model<object, object>;
8
8
  idAttribute: string;
9
9
  dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
@@ -12,7 +12,8 @@ declare const ModelCache: {
12
12
  measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
13
13
  subscriptions: import("./model.js").CanonicalModelSubscription[];
14
14
  CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
15
- }> | Model<Record<string, any>, Record<string, any>> | undefined;
15
+ invalidates: ResourceKeys[];
16
+ }> | undefined;
16
17
  put(cacheKey: string, model: Model | Collection, component?: Component): void;
17
18
  register(cacheKey: string, component?: Component): void;
18
19
  unregister(component: Component, ...cacheKeys: string[]): void;
@@ -1,7 +1,7 @@
1
1
  import Events from "./events.js";
2
2
  import sync, { type SyncOptions } from "./sync.js";
3
3
  import Collection, { type CollectionConstructor } from "./collection.js";
4
- import { NestedKeys, ResourceConfigObj } from "./types.js";
4
+ import { NestedKeys, ResourceConfigObj, ResourceKeys } from "./types.js";
5
5
  import CanonicalModel from "./canonical-model.js";
6
6
  export type ConstructorOptions = {
7
7
  collection?: Collection;
@@ -37,6 +37,7 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
37
37
  static measure: boolean | ((config: ResourceConfigObj) => boolean);
38
38
  static subscriptions: CanonicalModelSubscription[];
39
39
  static CanonicalModel: (new (...args: any[]) => CanonicalModel<any>) | null;
40
+ static invalidates: ResourceKeys[];
40
41
  toJSON(): T;
41
42
  sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
42
43
  get<K extends keyof T>(attr: K): T[K];
@@ -60,6 +61,7 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
60
61
  unsubscribe(): void;
61
62
  _removePeerSubscribers(CollectionClass?: CollectionConstructor): void;
62
63
  _updateSubscriptions(attrs?: Partial<T>, options?: SetOptions): void;
64
+ _invalidateRelated(): void;
63
65
  _getSubscriptions(): (CanonicalModelSubscription<Record<string, any>, Record<string, any>> | {
64
66
  Model: new (...args: any[]) => CanonicalModel<any>;
65
67
  idField: string;
@@ -1,6 +1,7 @@
1
1
  import { getNestedValue, isDeepEqual, result, uniqueId, urlError } from "./utils.js";
2
2
  import Events from "./events.js";
3
3
  import sync from "./sync.js";
4
+ import { invalidate } from "./model-cache.js";
4
5
  import CanonicalModelCache from "./canonical-model-cache.js";
5
6
  const RESERVED_OPTION_KEYS = [
6
7
  "Model",
@@ -45,6 +46,7 @@ export default class Model extends Events {
45
46
  static measure = false;
46
47
  static subscriptions = [];
47
48
  static CanonicalModel = null;
49
+ static invalidates = [];
48
50
  toJSON() {
49
51
  return { ...this.attributes };
50
52
  }
@@ -131,6 +133,7 @@ export default class Model extends Events {
131
133
  this._subscribe(serverAttrs);
132
134
  this.set(serverAttrs, { silent: true, ...options });
133
135
  this.triggerUpdate();
136
+ this._invalidateRelated();
134
137
  return [this, response];
135
138
  })
136
139
  .catch((response) => {
@@ -162,6 +165,7 @@ export default class Model extends Events {
162
165
  this._removePeerSubscribers(CollectionClass);
163
166
  }
164
167
  this.unsubscribe();
168
+ this._invalidateRelated();
165
169
  return [this, response];
166
170
  })
167
171
  .catch((response) => {
@@ -245,6 +249,15 @@ export default class Model extends Events {
245
249
  }
246
250
  }
247
251
  }
252
+ _invalidateRelated() {
253
+ const keys = [
254
+ ...this.constructor.invalidates,
255
+ ...(this.collection?.constructor?.invalidates ?? []),
256
+ ];
257
+ if (keys.length) {
258
+ window.setTimeout(() => invalidate(keys), 0);
259
+ }
260
+ }
248
261
  _getSubscriptions() {
249
262
  const { subscriptions, idAttribute, CanonicalModel } = this.constructor;
250
263
  return [
@@ -10,7 +10,7 @@ interface RequestOptions extends Pick<SyncOptions, "params"> {
10
10
  force?: boolean;
11
11
  lazy?: boolean;
12
12
  }
13
- export declare const getFromCache: (key: string) => Collection<object, object, {
13
+ export declare const getFromCache: (key: string) => Model<Record<string, any>, Record<string, any>> | Collection<object, object, {
14
14
  new (attributes?: object | undefined, options?: object & import("./model.js").SetOptions & import("./model.js").ConstructorOptions): Model<object, object>;
15
15
  idAttribute: string;
16
16
  dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
@@ -19,7 +19,8 @@ export declare const getFromCache: (key: string) => Collection<object, object, {
19
19
  measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
20
20
  subscriptions: import("./model.js").CanonicalModelSubscription[];
21
21
  CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
22
- }> | Model<Record<string, any>, Record<string, any>> | undefined;
22
+ invalidates: import("./types.js").ResourceKeys[];
23
+ }> | undefined;
23
24
  export declare const existsInCache: (key: string) => boolean;
24
25
  declare const _default: (key: string, Model: {
25
26
  new (data: Record<string, any>, options: RequestOptions["options"]): Model;
@@ -87,7 +87,7 @@ export function useResources(getResources, _props) {
87
87
  }
88
88
  });
89
89
  if (Object.keys(nextLoadingStates).some((ky) => nextLoadingStates[ky] !== loadingStates[ky])) {
90
- loaderDispatch({ type: "loading", payload: nextLoadingStates });
90
+ loaderDispatch({ type: "changed", payload: { loadingStates: nextLoadingStates, resources } });
91
91
  }
92
92
  useEffect(() => {
93
93
  if (resourcesToUpdate.length) {
@@ -122,7 +122,7 @@ export function useResources(getResources, _props) {
122
122
  setModels(modelAggregator([[name, config]]));
123
123
  loaderDispatch({
124
124
  type: "error",
125
- payload: { name, status },
125
+ payload: { name, status, resources },
126
126
  });
127
127
  });
128
128
  },
@@ -333,12 +333,12 @@ function partitionResources(resourcesToUpdate, loadingStates) {
333
333
  [memo[0], memo[1].concat([[name, config]])]
334
334
  : [memo[0].concat([[name, config]]), memo[1]], [[], []]);
335
335
  }
336
- function loaderReducer({ loadingStates, requestStatuses, hasInitiallyLoaded }, { type, payload = {} }) {
337
- switch (type) {
336
+ function loaderReducer({ loadingStates, requestStatuses, hasInitiallyLoaded }, action) {
337
+ switch (action.type) {
338
338
  case "error":
339
339
  case "loaded": {
340
- const { name, status, resources } = payload;
341
- let nextLoadingStates = { ...loadingStates, [getResourceState(name)]: type };
340
+ const { name, status, resources } = action.payload;
341
+ const nextLoadingStates = { ...loadingStates, [getResourceState(name)]: action.type };
342
342
  return {
343
343
  loadingStates: nextLoadingStates,
344
344
  requestStatuses: {
@@ -346,17 +346,19 @@ function loaderReducer({ loadingStates, requestStatuses, hasInitiallyLoaded }, {
346
346
  ...(status ? { [getResourceStatus(name)]: status } : {}),
347
347
  },
348
348
  hasInitiallyLoaded: hasInitiallyLoaded ||
349
- (type === "loaded" &&
350
- hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources)) &&
351
- !hasInitiallyLoaded),
349
+ (action.type === "loaded" &&
350
+ hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources))),
352
351
  };
353
352
  }
354
- case "loading":
353
+ case "changed": {
354
+ const { loadingStates: changedLoadingStates, resources } = action.payload;
355
+ const nextLoadingStates = { ...loadingStates, ...changedLoadingStates };
355
356
  return {
356
- loadingStates: { ...loadingStates, ...payload },
357
+ loadingStates: nextLoadingStates,
357
358
  requestStatuses,
358
- hasInitiallyLoaded,
359
+ hasInitiallyLoaded: hasInitiallyLoaded || hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources)),
359
360
  };
361
+ }
360
362
  default:
361
363
  return { loadingStates, requestStatuses, hasInitiallyLoaded };
362
364
  }
@@ -18,6 +18,7 @@ export type ResourceConfigObj = {
18
18
  [key: string]: any;
19
19
  };
20
20
  dependsOn?: boolean;
21
+ fetch?: boolean;
21
22
  force?: boolean;
22
23
  lazy?: boolean;
23
24
  resourceKey?: ResourceKeys;
@@ -55,7 +56,7 @@ export type UseResourcesResponse = {
55
56
  hasErrored: boolean;
56
57
  hasLoaded: boolean;
57
58
  hasInitiallyLoaded: boolean;
58
- refetch: (keys: ResourceKeys[]) => void;
59
+ refetch: (keys: ResourceKeys | ResourceKeys[]) => void;
59
60
  invalidate: typeof invalidate;
60
61
  setResourceState(newState: {
61
62
  [key: string]: any;
@@ -55,8 +55,9 @@ Using `dependsOn` in simple cases like the one highlighted in the [README](https
55
55
 
56
56
  // this assumes that the parent is handling the `hasErrored` state. if it is not, then
57
57
  // you may need to instead use:
58
+ // import {Utils} from 'resourcerer';
58
59
  shouldComponentUpdate(nextProps) {
59
- return !(nextProps.isLoading || areAnyPending(nextProps.myDependentLoadingState));
60
+ return !(nextProps.isLoading || Utils.isPending(nextProps.myDependentLoadingState));
60
61
  }
61
62
  ```
62
63
 
@@ -116,7 +117,20 @@ In this case, when the component is used as an order component (denoted by the p
116
117
 
117
118
  For all other uses of dependent resources, we should use `dependsOn`.
118
119
 
120
+ ## Unfetched Resources
119
121
 
122
+ Sometimes you want a Model instance in the cache _without_ hitting the network—for example, while composing a new resource in a form before it has an id. Pass `fetch: false` (or a boolean expression that evaluates to false) in the resource config:
123
+
124
+ ```js
125
+ const getResources = (props) => ({
126
+ todo: {
127
+ data: {id: props.id},
128
+ fetch: !!props.id
129
+ }
130
+ });
131
+ ```
132
+
133
+ When `fetch` is false, resourcerer still constructs and caches the model (initialized from `data`) and returns it to your component, but it does not call `model.fetch()`. See [Recaching newly-saved models](#recaching-newly-saved-models) for the common create-then-navigate pattern that builds on this.
120
134
 
121
135
  ## Loading Overlays
122
136
 
@@ -51,6 +51,15 @@ The number of milliseconds to keep all collections of this class in the cache af
51
51
 
52
52
  A boolean or function that accepts a [resource configuration object](https://github.com/noahgrant/resourcerer#nomenclature) and returns a boolean, telling resourcerer to track this collection's request time and report it via the `track` method setup in [configuration](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
53
53
 
54
+ ### `static` invalidates
55
+ `ResourceKeys[]`
56
+
57
+ Same as [Model `static invalidates`](/docs/model.md#static-invalidates): resource keys to remove from the cache after a successful write that goes through this collection's shared save/destroy invalidation path. Prefer declarative invalidation when related resources should clear together; use imperative [`invalidate`](https://github.com/noahgrant/resourcerer#cache-invalidation) for one-off cases.
58
+
59
+ ### `static` subscriptions / `static` CanonicalModel
60
+
61
+ For keeping denormalized fields in sync across models, see [Canonical Models](https://github.com/noahgrant/resourcerer#canonical-models).
62
+
54
63
  ### `static` idAttribute
55
64
 
56
65
  Use this as a shortcut when you don't want to define a custom Model class just because the collection doesn't contain the default id field (which is `'id'`), ie:
@@ -70,7 +79,7 @@ static idAttribute = 'name'
70
79
  constructor: (models: Array<Record<string, any> | Model>, options: object) => void
71
80
  ```
72
81
 
73
- The Collection's constructor gets passed any initial models, as well as the [options](https://github.com/noahgrant/resourcerer#path) from the executor function. Override this to add some custom logic or instance variables for the collection&mdash;just be sure to pass the arguments to its `.super()` call, as well:
82
+ The Collection's constructor gets passed any initial models, as well as the [`path`](https://github.com/noahgrant/resourcerer#path) fields from the executor function. Override this to add some custom logic or instance variables for the collection&mdash;just be sure to pass the arguments to its `.super()` call, as well:
74
83
 
75
84
  ```js
76
85
  class MyCollection extends Collection<ModelType> {
@@ -87,7 +96,7 @@ class MyCollection extends Collection<ModelType> {
87
96
  }
88
97
  ```
89
98
 
90
- Passing in a `Model` option or a `comparator` option to an instance's constructor will override the statically defined properties on its constructor. Other `path` fields (the ones passed from the executor function [options](https://github.com/noahgrant/resourcerer#path) property) are passed to the `url` as shown in the example above.
99
+ Passing in a `Model` option or a `comparator` option to an instance's constructor will override the statically defined properties on its constructor. Other [`path`](https://github.com/noahgrant/resourcerer#path) fields from the executor function are passed to the `url` as shown in the example above.
91
100
 
92
101
 
93
102
  ### add
@@ -95,14 +104,14 @@ Passing in a `Model` option or a `comparator` option to an instance's constructo
95
104
  add: (models: Record<string, any> | Model | Array<Record<string, any> | Model>, options: Object) => this
96
105
  ```
97
106
 
98
- Add a new entry or list of entries into the collection. Each entry can be an object of data or a Model instance. Will trigger an update in all subscribed components unless the `trigger: true` option is passed. You can also pass a `parse: true` option to run the model through its [parse](/docs/model.md#parse) method before setting its properties. If an entry already exists on the collection, the new properties will get merged into its existing model.
107
+ Add a new entry or list of entries into the collection. Each entry can be an object of data or a Model instance. Will trigger an update in all subscribed components unless the `silent: true` option is passed. You can also pass a `parse: true` option to run the model through its [parse](/docs/model.md#parse) method before setting its properties. If an entry already exists on the collection, the new properties will get merged into its existing model.
99
108
 
100
109
  ### create
101
110
  ```js
102
111
  create: (model: Record<string, any> | Model, options: Object) => Promise<[Model, Response]>
103
112
  ```
104
113
 
105
- Adds a new entry to the collection and persists it to the server. This is literally the equivalent to calling `collection.add()` and then `model.save()`. Because it also instantiates the new model, be sure to pass any path params you need in your url as the options argument (the same [options](https://github.com/noahgrant/resourcerer#options) in the resource config object). The returned Promise is the same as is returned from [Model#save](/docs/model.md#save). If the request errors, the model is auto-removed from the collection. Pass the `wait: true` option to wait to add the new model until after the save request returns. Subscribed components will update when the new entry is added as well as when the request returns.
114
+ Adds a new entry to the collection and persists it to the server. This is literally the equivalent to calling `collection.add()` and then `model.save()`. Because it also instantiates the new model, be sure to pass any path params you need in your url as the options argument (the same [`path`](https://github.com/noahgrant/resourcerer#path) fields in the resource config object). The returned Promise is the same as is returned from [Model#save](/docs/model.md#save). If the request errors, the model is auto-removed from the collection. Pass the `wait: true` option to wait to add the new model until after the save request returns. Subscribed components will update when the new entry is added as well as when the request returns.
106
115
 
107
116
  ***All .create() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
108
117
 
@@ -121,7 +130,7 @@ This is the method that `resourcerer` uses internally to get server data and set
121
130
  get: (identifier: string | number) => Model | undefined
122
131
  ```
123
132
 
124
- Collections index their Model instances by either the Model's [`idAttribute`](/docs/model.md#static-idattribute) or, equivalently as a shortcut, by the collection's own static [`modelIdAttribute`](#static-modelidattribute) property. The `.get()` method takes an id value and returns the quick-lookup model instance if one exists.
133
+ Collections index their Model instances by either the Model's [`idAttribute`](/docs/model.md#static-idattribute) or, equivalently as a shortcut, by the collection's own static [`idAttribute`](#static-idattribute) property. The `.get()` method takes an id value and returns the quick-lookup model instance if one exists.
125
134
 
126
135
  ### has
127
136
  ```js
@@ -35,14 +35,16 @@ The core methodology and functionality of `resourcerer` has not changed in versi
35
35
 
36
36
  1. The utility methods `haveAllLoaded`, `areAnyLoading`, and `haveAnyErrored` have been placed under a top-level `Utils` object and are now named `Utils.hasLoaded`, `Utils.isLoading`, and `Utils.hasErrored`, resepectively, to provide consistency with other loading state names. Their signatures have not changed.
37
37
 
38
- 1. The [refetch](/#refetching) method returned from `useResources` no longer accepts a function as an argument. Pass an array of resource keys directly instead:
38
+ 1. The [refetch](/#refetching) method returned from `useResources` no longer accepts a function as an argument. Pass a resource key or an array of resource keys directly instead:
39
39
 
40
40
  ```js
41
41
  // previously
42
42
  refetch(({todos}) => [todos]);
43
43
 
44
44
  // now
45
- refetch([todos]);
45
+ refetch("todos");
46
+ // or
47
+ refetch(["todos"]);
46
48
  ```
47
49
 
48
50
  1. [dependsOn](/#serial-requests) is no longer an array of strings that checks existence of prop fields. To be more versatile, it is a boolean, and will fetch the resource whenever its conditions evaluate to true:
package/docs/model.md CHANGED
@@ -65,7 +65,14 @@ An object or function that returns object with attribute keys and their default
65
65
 
66
66
  A boolean or function that accepts a [resource configuration object](https://github.com/noahgrant/resourcerer#nomenclature) and returns a boolean, telling resourcerer to track this model's request time and report it via the `track` method setup in [configuration](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
67
67
 
68
+ ### `static` invalidates
69
+ `ResourceKeys[]`
68
70
 
71
+ List of resource keys whose cache entries should be removed after a successful [`save`](#save) or [`destroy`](#destroy) on this model. Prefer this for declarative invalidation of related resources; use the imperative [`invalidate`](https://github.com/noahgrant/resourcerer#cache-invalidation) helper when you need one-off control from a component.
72
+
73
+ ### `static` subscriptions / `static` CanonicalModel
74
+
75
+ For keeping denormalized fields in sync across models, see [Canonical Models](https://github.com/noahgrant/resourcerer#canonical-models).
69
76
 
70
77
  ## Methods
71
78
 
@@ -75,7 +82,7 @@ A boolean or function that accepts a [resource configuration object](https://git
75
82
  constructor: (initialData: object, options: object) => void
76
83
  ```
77
84
 
78
- The Model's constructor gets passed any initial data, as well as the [options](https://github.com/noahgrant/resourcerer#options) from the executor function. Override this to add some custom logic or instance variables for the model&mdash;just be sure to pass the arguments to its `.super()` call, as well:
85
+ The Model's constructor gets passed any initial data, as well as the [`path`](https://github.com/noahgrant/resourcerer#path) fields from the executor function. Override this to add some custom logic or instance variables for the model&mdash;just be sure to pass the arguments to its `.super()` call, as well:
79
86
 
80
87
  ```ts
81
88
  class MyModel extends Model<ModelType> {
@@ -91,7 +98,7 @@ class MyModel extends Model<ModelType> {
91
98
  }
92
99
  ```
93
100
 
94
- Note that `this.id` is automatically set to whichever value is passed in at the [`idAttribute`](#static-idattribute) key (default: 'id'). Pass the `parse: true` option to have the data get run through the Model's `parse` method before getting set. Other [options](https://github.com/noahgrant/resourcerer#options) fields from the executor function are passed to the `url` as shown in the example above.
101
+ Note that `this.id` is automatically set to whichever value is passed in at the [`idAttribute`](#static-idattribute) key (default: 'id'). Pass the `parse: true` option to have the data get run through the Model's `parse` method before getting set. Other [`path`](https://github.com/noahgrant/resourcerer#path) fields from the executor function are passed to the `url` as shown in the example above.
95
102
 
96
103
 
97
104
  ### toJSON
@@ -198,6 +205,20 @@ Use this to remove the send a DELETE request at this model's url to the server.
198
205
  fetch: (options: Object) => Promise<[Model, Response]>
199
206
  ```
200
207
 
201
- This is the method that `resourcerer` uses internally to get server data and set its parsed response as models on the collection. This should rarely need to be used in your application. Subscribed components will update when the request returns.
208
+ This is the method that `resourcerer` uses internally to get server data and set its parsed response as attributes on the model. This should rarely need to be used in your application. Subscribed components will update when the request returns. Defaults to `GET`; override this method on a Model/Collection subclass when every fetch for that resource should use a different HTTP verb. `useResources` / `withResources` only forward `params` into this call.
202
209
 
203
210
  ***All .fetch() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
211
+
212
+ ### sync
213
+ ```js
214
+ sync: (model: Model | Collection, options: SyncOptions) => Promise<[any, Response]>
215
+ ```
216
+
217
+ Low-level networking used by [`fetch`](#fetch), [`save`](#save), and [`destroy`](#destroy). By default this is the package [`sync`](https://github.com/noahgrant/resourcerer/blob/main/lib/sync.ts) / `ajax` helpers (Fetch API under the hood). Override `Model.sync` (or `Collection.sync`) on a class or instance when you need custom transport. Common `SyncOptions` include:
218
+
219
+ * `method` — HTTP method (`GET` / `POST` / `PUT` / `PATCH` / `DELETE`)
220
+ * `params` — query string (GET) or JSON body (write methods)
221
+ * `minDuration` — minimum request duration in milliseconds (useful on `save` / `destroy`; not forwarded by resourcerer resource configs)
222
+ * `headers`, `url`, `attrs`, and anything else your [`prefilter`](https://github.com/noahgrant/resourcerer#configuring-resourcerer) / custom sync layer understands
223
+
224
+ Auth headers and global error handling belong in [`ResourcesConfig.prefilter`](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
@@ -24,19 +24,20 @@ it('runs a test', () => {
24
24
 
25
25
  ### Changing resource loading states
26
26
 
27
- When using `resourcerer`, you are using React function components that have no backing instances (and thus whose return from `render` is `null`). Therefore, we can't assert any prop values on components and we can't navigate a DOM tree the way we can when using classes. However, we can simply mock out `useResources` itself to test functionality. Because the `withResources` HOC also uses `useResources` under the hood, this will work when testing both. Here's an example (using [jest](https://jestjs.io/) and [react testing library](https://testing-library.com/docs/react-testing-library/intro/)) for testing how a component that uses `useResources` looks under a loading state:
27
+ When using `resourcerer`, you are using React function components that have no backing instances (and thus whose return from `render` is `null`). Therefore, we can't assert any prop values on components and we can't navigate a DOM tree the way we can when using classes. However, we can simply mock out `useResources` itself to test functionality. Because the `withResources` HOC also uses `useResources` under the hood, this will work when testing both. Here's an example (using [Vitest](https://vitest.dev/) or [Jest](https://jestjs.io/) and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/)) for testing how a component that uses `useResources` looks under a loading state:
28
28
 
29
29
  ```jsx
30
30
  import * as resourcerer from 'resourcerer';
31
31
  import {render} from '@testing-library/react';
32
+ import {vi} from 'vitest'; // or use jest.spyOn with Jest
32
33
 
33
34
  // ...
34
35
  it('shows a loader when in a loading state', () => {
35
- jest.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
36
+ vi.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
36
37
  ...props,
37
38
  hasLoaded: false,
38
39
  isLoading: true
39
- ));
40
+ }));
40
41
 
41
42
  const {container} = render(<MyComponent />);
42
43
 
@@ -47,12 +48,12 @@ it('shows a loader when in a loading state', () => {
47
48
  This should solve most of your use cases; you can return any mocked info you want, such as a noncritical loading state. You can also mock out `setResourceState`:
48
49
 
49
50
  ```jsx
50
- var setResourceMock = jest.fn();
51
+ var setResourceMock = vi.fn();
51
52
 
52
- jest.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
53
+ vi.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
53
54
  ...props,
54
55
  setResourceState: setResourceMock
55
- ));
56
+ }));
56
57
  ```
57
58
 
58
59
  Keep in mind that in this case the calls to `setResourceState` won't actually go through, and so state won't persist.
@@ -41,7 +41,7 @@ interface Todo {
41
41
  name: string;
42
42
  }
43
43
 
44
- export default TodosCollection extends Collection<Todo> {
44
+ export default class TodosCollection extends Collection<Todo> {
45
45
  url({userId}: {userId: string}) {
46
46
  return `/${userId}/todos`;
47
47
  }
@@ -98,7 +98,7 @@ function MyComponent(props) {
98
98
  } = useResources(({userId}) => ({todos: {params: {userId}}}), {ursdI: "oops"});
99
99
  ```
100
100
 
101
- But inlining executor functions leaves you susceptible to [the subtle bug where you are always reading from current props](https://github.com/noahgrant/resourcerer/tree/typescript?tab=readme-ov-file#differences-between-useresources-and-withresources). Executor functions can also get pretty involved, so it's nice to extract it. You still get good type hints, but you'll need to type out your props:
101
+ But inlining executor functions leaves you susceptible to [the subtle bug where you are always reading from current props](https://github.com/noahgrant/resourcerer#differences-between-useresources-and-withresources). Executor functions can also get pretty involved, so it's nice to extract it. You still get good type hints, but you'll need to type out your props:
102
102
 
103
103
  ```tsx
104
104
  // type out these props
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "github.com/noahgrant/resourcerer"
package/resourcerer.d.ts CHANGED
@@ -16,6 +16,7 @@ declare module "resourcerer" {
16
16
  export type ResourceConfigObj<K extends ResourceKeys> = {
17
17
  data?: Partial<GetModelOptions<InstanceType<ModelMap[K]>>[0]>;
18
18
  dependsOn?: boolean;
19
+ fetch?: boolean;
19
20
  force?: boolean;
20
21
  lazy?: boolean;
21
22
  noncritical?: boolean;
@@ -29,6 +30,7 @@ declare module "resourcerer" {
29
30
  model: InstanceType<ModelMap[K]>,
30
31
  props: Record<string, any>
31
32
  ) => { [key: string]: any };
33
+ resourceKey?: ResourceKeys;
32
34
  };
33
35
 
34
36
  export interface ModelMap {}
@@ -1,4 +1,5 @@
1
1
  import * as sync from "../lib/sync";
2
+ import * as modelCache from "../lib/model-cache";
2
3
  import CanonicalModel from "../lib/canonical-model";
3
4
  import { canonicalModelCache } from "../lib/canonical-model-cache";
4
5
 
@@ -1156,6 +1157,126 @@ describe("Model", () => {
1156
1157
  ]);
1157
1158
  });
1158
1159
  });
1160
+
1161
+ describe("invalidates", () => {
1162
+ beforeEach(() => {
1163
+ vi.useFakeTimers();
1164
+ vi.spyOn(modelCache, "invalidate");
1165
+ });
1166
+
1167
+ afterEach(() => {
1168
+ vi.useRealTimers();
1169
+ modelCache.invalidate.mockRestore();
1170
+ });
1171
+
1172
+ it("has an empty invalidates list by default", () => {
1173
+ expect(Model.invalidates).toEqual([]);
1174
+ });
1175
+
1176
+ it("does not call invalidate after save when invalidates is empty", async () => {
1177
+ model = new Model();
1178
+ await model.save();
1179
+ vi.runAllTimers();
1180
+ expect(modelCache.invalidate).not.toHaveBeenCalled();
1181
+ });
1182
+
1183
+ it("calls invalidate with the model's invalidates keys after a successful save", async () => {
1184
+ class _Model extends Model {
1185
+ static invalidates = ["todos", "user"];
1186
+ }
1187
+
1188
+ model = new _Model();
1189
+ await model.save();
1190
+ expect(modelCache.invalidate).not.toHaveBeenCalled();
1191
+
1192
+ vi.runAllTimers();
1193
+ expect(modelCache.invalidate).toHaveBeenCalledWith(["todos", "user"]);
1194
+ });
1195
+
1196
+ it("calls invalidate with the model's invalidates keys after a successful destroy", async () => {
1197
+ class _Model extends Model {
1198
+ static invalidates = ["todos"];
1199
+ }
1200
+
1201
+ model = new _Model({ id: "1234" });
1202
+ await model.destroy();
1203
+ expect(modelCache.invalidate).not.toHaveBeenCalled();
1204
+
1205
+ vi.runAllTimers();
1206
+ expect(modelCache.invalidate).toHaveBeenCalledWith(["todos"]);
1207
+ });
1208
+
1209
+ it("does not call invalidate after a failed save", async () => {
1210
+ class _Model extends Model {
1211
+ static invalidates = ["todos"];
1212
+ }
1213
+
1214
+ sync.default.mockRejectedValue(new Error("failed"));
1215
+ model = new _Model();
1216
+
1217
+ try {
1218
+ await model.save();
1219
+ } catch (_) {
1220
+ // expected
1221
+ }
1222
+
1223
+ vi.runAllTimers();
1224
+ expect(modelCache.invalidate).not.toHaveBeenCalled();
1225
+ });
1226
+
1227
+ it("does not call invalidate after a failed destroy", async () => {
1228
+ class _Model extends Model {
1229
+ static invalidates = ["todos"];
1230
+ }
1231
+
1232
+ sync.default.mockRejectedValue(new Error("failed"));
1233
+ model = new _Model({ id: "1234" });
1234
+
1235
+ try {
1236
+ await model.destroy();
1237
+ } catch (_) {
1238
+ // expected
1239
+ }
1240
+
1241
+ vi.runAllTimers();
1242
+ expect(modelCache.invalidate).not.toHaveBeenCalled();
1243
+ });
1244
+
1245
+ it("includes invalidates keys from the parent collection", async () => {
1246
+ class _Model extends Model {
1247
+ static invalidates = ["todos"];
1248
+ }
1249
+
1250
+ class _Collection extends Collection {
1251
+ static invalidates = ["user"];
1252
+ }
1253
+
1254
+ collection = new _Collection();
1255
+ model = new _Model({ id: "1234" }, { collection });
1256
+ await model.save();
1257
+ vi.runAllTimers();
1258
+ expect(modelCache.invalidate).toHaveBeenCalledWith(["todos", "user"]);
1259
+ });
1260
+
1261
+ it("defers invalidation so refetch can still find the model in the same .then() chain", async () => {
1262
+ class _Model extends Model {
1263
+ static invalidates = ["todos"];
1264
+ }
1265
+
1266
+ model = new _Model();
1267
+
1268
+ let modelStillInCacheDuringSave = false;
1269
+
1270
+ await model.save().then(() => {
1271
+ modelStillInCacheDuringSave = true;
1272
+ expect(modelCache.invalidate).not.toHaveBeenCalled();
1273
+ });
1274
+
1275
+ expect(modelStillInCacheDuringSave).toBe(true);
1276
+ vi.runAllTimers();
1277
+ expect(modelCache.invalidate).toHaveBeenCalled();
1278
+ });
1279
+ });
1159
1280
  });
1160
1281
 
1161
1282
  class CanonicalTestModel extends CanonicalModel {}