resourcerer 1.0.0-beta-5 → 1.0.3

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  <img src="https://user-images.githubusercontent.com/1355779/61337603-f9fffd80-a7ea-11e9-9cb3-fa82e044c86e.png" alt="Resourcerer Icon" height="200" width="200" />
2
2
 
3
- # resourcerer (now in 1.0-beta!)
3
+ # resourcerer
4
4
 
5
5
  `resourcerer` is a library for declaratively fetching and caching your application's data. Its powerful [`useResources`](#useresources) React hook or [`withResources`](#withresources) higher-order React component (HOC) allows you to easily construct a component's data flow, including:
6
6
 
@@ -12,13 +12,13 @@
12
12
 
13
13
  Additional features include:
14
14
 
15
+ * fully declarative (no more writing any imperative Fetch API calls)
15
16
  * first-class loading and error state support
16
17
  * smart client-side caching
17
18
  * refetching
18
19
  * updating a component when a resource updates
19
20
  * zero dependencies
20
21
  * < 10kB!
21
- * ...and more
22
22
 
23
23
  Getting started is easy:
24
24
 
@@ -56,13 +56,12 @@ import 'js/core/resourcerer-config';
56
56
  1. ### useResources
57
57
 
58
58
  ```jsx
59
- import React from 'react';
60
59
  import {useResources} from 'resourcerer';
61
60
 
62
61
  const getResources = ({TODOS}, props) => ({[TODOS]: {}});
63
62
 
64
63
  function MyComponent(props) {
65
- var {
64
+ const {
66
65
  isLoading,
67
66
  hasErrored,
68
67
  hasLoaded,
@@ -134,7 +133,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
134
133
  1. [params](#params)
135
134
  1. [options](#options)
136
135
  1. [noncritical](#noncritical)
137
- 1. [forceFetch](#forcefetch)
136
+ 1. [force](#force)
138
137
  1. [Custom Resource Names](#custom-resource-names)
139
138
  1. [prefetches](#prefetches)
140
139
  1. [data](#data)
@@ -178,7 +177,7 @@ module: {
178
177
 
179
178
  1. **ResourceKeys**. These are the keys added to the `ModelMap` (discussed above in the introduction) that link to your model constructors. They are passed to the executor functions and are used to tell the hook or HOC which resources to request.
180
179
 
181
- 1. **Executor Function**. The executor function is a function that both the hook and HOC accept that declaratively describes which resources to request and with what config options. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
180
+ 1. **Executor Function**. The executor function is a function that both the hook and HOC accept that declaratively describes which resources to request and with what config options. In these docs you'll often see it assigned to a variable called `getResources`. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
182
181
 
183
182
  ```js
184
183
  const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}});
@@ -203,7 +202,7 @@ module: {
203
202
  };
204
203
  ```
205
204
 
206
- It returns an object whose keys represent the resources to fetch and whose values are resource configuration objects that we'll discuss later (and is highlighted below).
205
+ It returns an object whose keys represent the resources to fetch and whose values are **Resource Configuration Objects** that we'll discuss later (and is highlighted below).
207
206
 
208
207
  1. **Resource Configuration Object (resource config)**. In the object returned by our executor function, each entry has a key equal to one of the `ResourceKeys` and whose value we will refer to in this document as a Resource Configuration Object. It holds the declarative instructions that `useResources` and `withResources` will use to request the resource.
209
208
 
@@ -218,7 +217,7 @@ Okay, back to the initial example. Let's take a look at our `useResources` usage
218
217
  const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
219
218
 
220
219
  export default function MyComponent(props) {
221
- var resources = useResources(getResources, props);
220
+ const resources = useResources(getResources, props);
222
221
 
223
222
  // ...
224
223
  }
@@ -264,7 +263,7 @@ const getResources = ({TODOS, USERS}, props) => ({
264
263
  });
265
264
 
266
265
  function MyClassWithTodosAndAUsers(props) {
267
- var resources = useResources(getResources, props);
266
+ const resources = useResources(getResources, props);
268
267
  }
269
268
  ```
270
269
 
@@ -284,7 +283,7 @@ Here’s how might use that to our advantage in `MyClassWithTodosAndAUsers` :
284
283
  import {haveAllLoaded} from 'resourcerer';
285
284
 
286
285
  function MyClassWithTodosAndAUsers(props) {
287
- var {
286
+ const {
288
287
  isLoading,
289
288
  hasErrored,
290
289
  hasLoaded,
@@ -389,7 +388,7 @@ const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}}
389
388
 
390
389
  // hook
391
390
  function MyComponent(props) {
392
- var resources = useResources(getResources, props);
391
+ const resources = useResources(getResources, props);
393
392
 
394
393
  // ...
395
394
  }
@@ -492,12 +491,12 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
492
491
 
493
492
 
494
493
 
495
- ### forceFetch
494
+ ### force
496
495
 
497
- Sometimes you want the latest of a resource, bypassing whatever model has already been cached in your application. To accomplish this, simply pass a `forceFetch: true` in a resource's config. The force-fetched response will replace any prior model in the cache, but may itself get replaced by a subsequent `forceFetch: true` request for the resource.
496
+ Sometimes you want the latest of a resource, bypassing whatever model has already been cached in your application. To accomplish this, simply pass a `force: true` in a resource's config. The force-fetched response will replace any prior model in the cache, but may itself get replaced by a subsequent `force: true` request for the resource.
498
497
 
499
498
  ```js
500
- @withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {forceFetch: true}}))
499
+ @withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {force: true}}))
501
500
  class MyComponentWithLatestStats extends React.Component {}
502
501
  ```
503
502
 
@@ -509,7 +508,7 @@ Passing a `modelKey: <ResourceKeys>` option allows you to pass a custom name as
509
508
  const getResources = (ResourceKeys, props) => ({myRadTodos: {modelKey: ResourceKeys.TODOS});
510
509
 
511
510
  export default function MyComponentWithTodos {
512
- var {
511
+ const {
513
512
  myRadTodosCollection,
514
513
  myRadTodosLoadingState,
515
514
  myRadTodosStatus,
@@ -566,7 +565,7 @@ Pass in a data hash to initialize a Model instance with data before initially fe
566
565
  getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
567
566
 
568
567
  function MyCustomerComponent(props) {
569
- var {customerModel} = useResources(getResources, props);
568
+ const {customerModel} = useResources(getResources, props);
570
569
 
571
570
  // now you can reference the id directly on the model
572
571
  console.log(customerModel.get('id')); // or the id shorthand, customerModel.id
@@ -595,10 +594,10 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
595
594
 
596
595
  ```js
597
596
  function MyComponent(props) {
598
- var {myModel} = useResources(getResources, props),
599
- onSave = () => myModel.save({foo: 'bar'})
600
- .then([model]) => // ...)
601
- .catch(() => alert('request failed'));
597
+ const {myModel} = useResources(getResources, props),
598
+ onSave = () => myModel.save({foo: 'bar'})
599
+ .then([model]) => // ...)
600
+ .catch(() => alert('request failed'));
602
601
 
603
602
  return <button onClick={onSave}>Persist model</button>;
604
603
  }
@@ -618,8 +617,8 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
618
617
 
619
618
  ```js
620
619
  function TodoDetails(props) {
621
- var {hasLoaded, todosCollection} = useResources(getResources, props),
622
- todoModel = todosCollection.get(props.id),
620
+ const {hasLoaded, todosCollection} = useResources(getResources, props),
621
+ todoModel = todosCollection.get(props.id),
623
622
 
624
623
  onSaveTodo = {
625
624
  // set some loading state...
@@ -656,8 +655,7 @@ Each one of these methods exhibit the following behaviors:
656
655
  **Note:**
657
656
  1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
658
657
  1. All write calls must have a `.catch` attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.
659
- 2.
660
-
658
+
661
659
  ## Serial Requests
662
660
 
663
661
  In most situations, all resource requests should be parallelized; but that’s not always possible. Every so often, there may be a situation where one request depends on the result of another. For these cases, we have the `dependsOn` resource config option and the `provides` resource config option. These are probably best explained by example, so here is a simplified instance from the [Sift](https://sift.com) Console, where we load a queue item that has info about a user, but we can't get further user information until we know what user id belongs to this queue item.
@@ -704,7 +702,7 @@ const getResources = ({QUEUE_ITEM, USER}, props) => ({
704
702
 
705
703
  export default function QueueItemPage(props) {
706
704
  // activeState and userId are internal state within `useResources` and returned
707
- var {
705
+ const {
708
706
  activeState,
709
707
  userId,
710
708
  userModel,
@@ -728,7 +726,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
728
726
 
729
727
  ```js
730
728
  function MyComponent({start_time, ...props}) {
731
- var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
729
+ const {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
732
730
 
733
731
  // ...
734
732
  ```
@@ -737,7 +735,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
737
735
 
738
736
  ```js
739
737
  function MyComponent(props) {
740
- var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
738
+ const {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
741
739
 
742
740
  // ...
743
741
  ```
@@ -748,7 +746,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
748
746
  const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
749
747
 
750
748
  function MyComponent(props) {
751
- var {todosCollection} = useResources(getResources, props);
749
+ const {todosCollection} = useResources(getResources, props);
752
750
 
753
751
  // ...
754
752
  ```
@@ -861,7 +859,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
861
859
 
862
860
  ```js
863
861
  function MyComponent(props) {
864
- var {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
862
+ const {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
865
863
 
866
864
  // ...
867
865
 
@@ -1012,12 +1010,12 @@ ResourcesConfig.set(configObj);
1012
1010
 
1013
1011
  // component1
1014
1012
  function MyComponent({category, ...props}) {
1015
- var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1013
+ const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1016
1014
  }
1017
1015
 
1018
1016
  // component2--identical to the first
1019
1017
  function MyComponent({category, ...props}) {
1020
- var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1018
+ const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1021
1019
  }
1022
1020
  ```
1023
1021
 
package/lib/model.js CHANGED
@@ -240,10 +240,7 @@ export default class Model {
240
240
  if (!options.wait) {
241
241
  this.set(attrs, options);
242
242
  } else {
243
- // sneaky: this will show up at this point if you .toJSON(), but it will not
244
- // be associated with an update. this is so that in the sync method, they can get all
245
- // attributes via .toJSON()
246
- this.attributes = {...this.attributes, ...attrs};
243
+ options.attrs = {...this.attributes, ...attrs};
247
244
  }
248
245
 
249
246
  options.method = this.isNew() ? 'POST' : options.patch ? 'PATCH' : 'PUT';
package/lib/request.js CHANGED
@@ -38,7 +38,7 @@ export const existsInCache = (key) => !!ModelCache.get(key);
38
38
  * * data {object|object[]} - attributes or models to pass a Model or Collection instance, resp.
39
39
  * * params {object} - query params to pass into the fetch method
40
40
  * * fetch {boolean} - whether fetch the model after creation
41
- * * forceFetch {boolean} - force the fetch to be made if the model is already cached
41
+ * * force {boolean} - force the fetch to be made if the model is already cached
42
42
  * * method {string} - request type (GET|POST|PUT|DELETE)
43
43
  * * options {object} - options to pass to the Model constructor
44
44
  * * prefetch {boolean} - whether the request should be treated as a prefetched resource
@@ -55,19 +55,22 @@ export default (key, Model, options={}) => {
55
55
  params: {},
56
56
  options: {},
57
57
  fetch: true,
58
- forceFetch: false,
58
+ force: false,
59
+ lazy: false,
59
60
  method: 'GET',
60
61
  ...options
61
62
  };
62
63
 
63
64
  if (!loadingCache[key]) {
64
65
  _promise = new Promise((resolve, reject) => {
65
- if (!model || options.forceFetch) {
66
+ if (!model || model.lazy || options.force) {
66
67
  model = model || new Model(options.data, options.options);
67
68
 
68
- if (options.fetch) {
69
+ if (options.fetch && !options.lazy) {
69
70
  addToLoadingCache = true;
70
71
 
72
+ delete model.lazy;
73
+
71
74
  model.fetch({params: options.params}).then(
72
75
  ([newModel, response]) => {
73
76
  delete loadingCache[key];
@@ -80,6 +83,10 @@ export default (key, Model, options={}) => {
80
83
  }
81
84
  );
82
85
  } else {
86
+ // lazy means resolove but don't fetch yet; it will get updates from other components
87
+ // we only want to do this if a model is not yet in the cache
88
+ options.lazy && !ModelCache.get(key) ? model.lazy = true : null;
89
+
83
90
  ModelCache.put(key, model, options.component);
84
91
  resolve([model]);
85
92
  }
@@ -44,6 +44,8 @@ const SPREAD_PROVIDES_CHAR = '_';
44
44
  * a value to be set for the prop. If the key is equal to
45
45
  * SPREAD_PROVIDES_CHAR, then the return value of the transform function
46
46
  * is spread for dynamically-provided props.
47
+ * * force {boolean} - force a fetch request regardless of whether the model
48
+ * is already in the cache
47
49
  * * prefetch {object} - an individual map of expected future props to fetch
48
50
  * a new resource and store it in the cache. it will not, however, get
49
51
  * passed down to the child (no loading states, either)
@@ -497,19 +499,20 @@ function findCacheKey(resource, getResources, props) {
497
499
  * @param {object} props - current component props
498
500
  * @param {LoadingStates} defaultState - state to return if resource already exists in cache;
499
501
  * in most circumstances, this should be the LOADED state as you might expect. However, when we
500
- * prep resources to be re-fetched, in order to keep the loading state in sync with its model
501
- * state, even a cached resource should be temporarily in a LOADING state (if cached, this will
502
- * be corrected in the next microtask and before the JS stack is completed, so the LOADING state
503
- * should never be shown in the UI, despite render being called multiple times).
502
+ * prep resources to be re-fetched or if models were previously created lazily (without fetching),
503
+ * in order to keep the loading state in sync with its model state, even a cached resource should
504
+ * be temporarily in a LOADING state (if cached, this will be corrected in the next microtask and
505
+ * before the JS stack is completed, so the LOADING state should never be shown in the UI, despite
506
+ * render being called multiple times).
504
507
  * @return {object} state object with resource state keys as keys and the loading
505
508
  * state as values
506
509
  */
507
510
  function buildResourcesLoadingState(resources, props, defaultState=LoadingStates.LOADED) {
508
511
  return resources.reduce((state, [name, config]) => Object.assign(state, {
509
- [getResourceState(name)]:
510
- !config.refetch && (shouldBypassFetch(props, [name, config]) || getModelFromCache(config)) ?
511
- defaultState :
512
- (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
512
+ [getResourceState(name)]: !config.refetch && (shouldBypassFetch(props, [name, config]) ||
513
+ (getModelFromCache(config) && !getModelFromCache(config).lazy)) ?
514
+ defaultState :
515
+ (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
513
516
  }), {});
514
517
  }
515
518
 
@@ -681,10 +684,10 @@ function modelAggregator(resources) {
681
684
 
682
685
  /**
683
686
  * Separates out resources between those that are loading and those that have loaded. The latter
684
- * won't need to get passed to fetchResources, but the former will. Make sure that prefetched
685
- * resources get added to those that are loading so that the request gets made. Since prefetched
686
- * models don't factor into loading states, there's no concern that they get passed to
687
- * fetchResources even if they have been cached.
687
+ * won't need to get passed to fetchResources, but the former will. Make sure that prefetched,
688
+ * refetched, and lazy resources get added to those that are loading so that the request gets made.
689
+ * Since prefetched models don't factor into loading states, there's no concern that they get passed
690
+ * to fetchResources even if they have been cached.
688
691
  *
689
692
  * @param {array[]} resourcesToUpdate - resource configs to partition
690
693
  * @param {object} loadingStates - contains upcoming loading states for each resource
@@ -693,7 +696,8 @@ function modelAggregator(resources) {
693
696
  */
694
697
  function partitionResources(resourcesToUpdate, loadingStates) {
695
698
  return resourcesToUpdate.reduce((memo, [name, config]) =>
696
- config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
699
+ config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ||
700
+ getModelFromCache(config)?.lazy ?
697
701
  [memo[0], memo[1].concat([[name, config]])] :
698
702
  [memo[0].concat([[name, config]]), memo[1]],
699
703
  [[], []]);
@@ -817,7 +821,7 @@ function fetchResources(resources, props, {
817
821
  fetch: !UnfetchedResources.has(modelKey),
818
822
  params,
819
823
  component,
820
- forceFetch: refetch,
824
+ force: refetch,
821
825
  ...rest
822
826
  }).then(
823
827
  // success callback, where we track request time and add any dependent props or models
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.0.0-beta-5",
3
+ "version": "1.0.3",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": [
@@ -314,7 +314,7 @@ describe('Model', () => {
314
314
 
315
315
  result = model.save({three: 'three'}, {wait: true});
316
316
  expect(callback).not.toHaveBeenCalled();
317
- expect(model.toJSON()).toEqual({one: 'one', three: 'three'});
317
+ expect(model.toJSON()).toEqual({one: 'one'});
318
318
 
319
319
  await result;
320
320
 
@@ -126,10 +126,7 @@ describe('Request', () => {
126
126
 
127
127
  describe('if the \'fetch\' option is false', () => {
128
128
  it('calls the resolve immediately', async() => {
129
- var model;
130
-
131
- request('nofetch', Model, {component, fetch: false})
132
- .then(([_model]) => model = _model);
129
+ var [model] = await request('nofetch', Model, {component, fetch: false});
133
130
 
134
131
  await waitsFor(() => model instanceof Model);
135
132
 
@@ -140,8 +137,7 @@ describe('Request', () => {
140
137
  var model;
141
138
 
142
139
  expect(ModelCache.get('nofetch')).not.toBeDefined();
143
- request('nofetch', Model, {component, fetch: false})
144
- .then(([_model]) => model = _model);
140
+ [model] = await request('nofetch', Model, {component, fetch: false});
145
141
 
146
142
  await waitsFor(() => model instanceof Model);
147
143
 
@@ -263,7 +259,7 @@ describe('Request', () => {
263
259
  });
264
260
  });
265
261
 
266
- describe('requested with {forceFetch: true}', () => {
262
+ describe('requested with {force: true}', () => {
267
263
  var startModel,
268
264
  finalModel;
269
265
 
@@ -273,7 +269,7 @@ describe('Request', () => {
273
269
  startModel = await request('bar', Model, {component});
274
270
  Model.prototype.fetch.mockClear();
275
271
 
276
- finalModel = await request('bar', Model, {component, forceFetch: true});
272
+ finalModel = await request('bar', Model, {component, force: true});
277
273
  });
278
274
 
279
275
  afterEach(() => {
@@ -288,6 +284,53 @@ describe('Request', () => {
288
284
  expect(startModel).toEqual(finalModel);
289
285
  });
290
286
  });
287
+
288
+ describe('with the \'lazy\' option', () => {
289
+ it('returns a new model without fetching', async() => {
290
+ await request('lazy', Model, {component, lazy: true});
291
+
292
+ expect(Model.prototype.fetch).not.toHaveBeenCalled();
293
+ expect(ModelCache.put).toHaveBeenCalled();
294
+ });
295
+
296
+ it('returns an existing model without fetching', async() => {
297
+ var existingModel = new Model(),
298
+ model;
299
+
300
+ ModelCache.put('lazy', existingModel, component);
301
+ [model] = await request('lazy', Model, {component, lazy: true});
302
+
303
+ expect(Model.prototype.fetch).not.toHaveBeenCalled();
304
+ expect(ModelCache.put).toHaveBeenCalled();
305
+ expect(existingModel).toEqual(model);
306
+ });
307
+
308
+ it('fetches when another component requests the same model without lazy option', async() => {
309
+ var [model] = await request('lazy', Model, {component, lazy: true});
310
+
311
+ expect(model.lazy).toBe(true);
312
+ expect(Model.prototype.fetch).not.toHaveBeenCalled();
313
+
314
+ [model] = await request('lazy', Model, {component});
315
+ expect(model.lazy).not.toBeDefined();
316
+ expect(Model.prototype.fetch).toHaveBeenCalled();
317
+
318
+ Model.prototype.fetch.mockClear();
319
+
320
+ // now if we ask for lazy again, followed by another non-lazy, it's already in the cache and
321
+ // we will not re-fetch
322
+ [model] = await request('lazy', Model, {component, lazy: true});
323
+ expect(model.lazy).not.toBeDefined();
324
+ [model] = await request('lazy', Model, {component});
325
+ expect(model.lazy).not.toBeDefined();
326
+ expect(Model.prototype.fetch).not.toHaveBeenCalled();
327
+
328
+ // now with two lazy requests (ie from different components), it still does not get fetched
329
+ await request('lazy', Model, {component, lazy: true});
330
+ await request('lazy', Model, {component: {}, lazy: true});
331
+ expect(Model.prototype.fetch).not.toHaveBeenCalled();
332
+ });
333
+ });
291
334
  });
292
335
 
293
336
  describe('when using getFromCache', () => {