resourcerer 1.0.0-alpha-3 → 1.0.0-beta-4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.0.0-alpha-3",
3
+ "version": "1.0.0-beta-4",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": [
@@ -43,6 +43,13 @@ describe('Collection', () => {
43
43
  expect(collection.Model).toEqual(__Model);
44
44
  });
45
45
 
46
+ it('unreserved option items are assigned to a `urlOptions` instance property', () => {
47
+ collection = new Collection([], {one: 1, two: 2, comparator: 'foo', parse: true});
48
+
49
+ expect(collection.urlOptions).toEqual({one: 1, two: 2});
50
+ expect(collection.toJSON()).toEqual([]);
51
+ });
52
+
46
53
  it('adds any models passed to its models list', () => {
47
54
  var model1 = new Model,
48
55
  model2 = new Model;
@@ -4,11 +4,10 @@ import Model from '../lib/model';
4
4
  export class UserModel extends Model {
5
5
  key = 'user'
6
6
 
7
- constructor(attrs, options={}) {
8
- super(attrs, options);
7
+ constructor(attributes, options={}) {
8
+ super(attributes, options);
9
9
 
10
10
  this.userId = options.userId;
11
- this.fraudLevel = options.fraudLevel;
12
11
  }
13
12
 
14
13
  url() {
@@ -39,14 +38,8 @@ export class DecisionsCollection extends Collection {
39
38
  export class NotesModel extends Model {
40
39
  key = 'notes'
41
40
 
42
- constructor(attributes, options={}) {
43
- super(attributes, options);
44
-
45
- this.userId = options.userId;
46
- }
47
-
48
- url() {
49
- return `/root/${this.userId}/notes`;
41
+ url({userId}) {
42
+ return `/root/${userId}/notes`;
50
43
  }
51
44
 
52
45
  static cacheFields = ['userId']
@@ -55,17 +48,11 @@ export class NotesModel extends Model {
55
48
  export class SearchQueryModel extends Model {
56
49
  key = 'search'
57
50
 
58
- constructor(attributes, options={}) {
59
- super(attributes, options);
60
-
61
- this.userId = options.userId;
62
- }
63
-
64
51
  fetch(options={}) {
65
52
  options = {
66
53
  ...options,
67
54
  contentType: 'application/json',
68
- data: JSON.stringify(options.data),
55
+ params: JSON.stringify(options.params),
69
56
  type: 'POST'
70
57
  };
71
58
 
@@ -117,13 +104,7 @@ export class LabelInstanceModel extends Model {
117
104
  export class AccountConfigModel extends Model {
118
105
  key = 'accountConfig'
119
106
 
120
- constructor(attrs, options={}) {
121
- super(attrs, options);
122
-
123
- this.accountId = options.accountId;
124
- }
125
-
126
- url() {
127
- return `/root/accounts/${this.accountId}/config`;
107
+ url({accountId}) {
108
+ return `/root/accounts/${accountId}/config`;
128
109
  }
129
110
  }
@@ -64,6 +64,12 @@ describe('Model', () => {
64
64
  expect(model.toJSON()).toEqual({});
65
65
  });
66
66
 
67
+ it('unreserved option items are assigned to a `urlOptions` instance property', () => {
68
+ model = new Model({}, {one: 1, two: 2, parse: true, silent: true});
69
+
70
+ expect(model.urlOptions).toEqual({one: 1, two: 2});
71
+ });
72
+
67
73
  it('can optionally have defaults that are a function', () => {
68
74
  class _Model extends Model {
69
75
  static defaults = {one: 1, two: 2}
@@ -470,6 +476,22 @@ describe('Model', () => {
470
476
  model = new _Model({name: 'noah?grant'}, {collection});
471
477
  expect(model.url()).toEqual('/library/noah%3Fgrant');
472
478
  });
479
+
480
+ it('is called by default with its urlOptions', () => {
481
+ class _Model extends Model {
482
+ urlRoot({section}) {
483
+ return `/library/${section}`;
484
+ }
485
+ }
486
+
487
+ model = new _Model({}, {section: 'nature'});
488
+ expect(model.url()).toEqual('/library/nature');
489
+
490
+ collection = new Collection();
491
+ collection.url = ({section}) => `/library/${section}`;
492
+ model = new Model({}, {collection, section: 'history'});
493
+ expect(model.url()).toEqual('/library/history');
494
+ });
473
495
  });
474
496
 
475
497
  describe('parse', () => {
@@ -6,9 +6,9 @@ import prefetch from '../lib/prefetch';
6
6
  import ReactDOM from 'react-dom';
7
7
 
8
8
  const renderNode = document.createElement('div');
9
- const getResources = (props, {DECISIONS, USER}) => ({
9
+ const getResources = ({DECISIONS, USER}, props) => ({
10
10
  [USER]: {
11
- data: {home: props.home, source: props.source},
11
+ params: {home: props.home, source: props.source},
12
12
  options: {userId: props.userId}
13
13
  },
14
14
  [DECISIONS]: {}
@@ -30,7 +30,7 @@ describe('prefetch', () => {
30
30
  jest.useRealTimers();
31
31
  });
32
32
 
33
- it('correctly turns the config object into cache key, data, and options', () => {
33
+ it('correctly turns the config object into cache key, params, and options', () => {
34
34
  var oldFields = UserModel.cacheFields;
35
35
 
36
36
  UserModel.cacheFields = ['userId', 'source'];
@@ -42,7 +42,7 @@ describe('prefetch', () => {
42
42
  expect(Request.default.mock.calls[0][1]).toEqual(UserModel);
43
43
  expect(Request.default.mock.calls[0][2]).toEqual({
44
44
  options: {userId: 'noah'},
45
- data: {home: 'sf', source: 'hbase'},
45
+ params: {home: 'sf', source: 'hbase'},
46
46
  prefetch: true
47
47
  });
48
48
 
@@ -1,6 +1,5 @@
1
- import request, {existsInCache, getFirstArgPropertyName, getFromCache} from '../lib/request';
1
+ import request, {existsInCache, getFromCache} from '../lib/request';
2
2
 
3
- import Collection from '../lib/collection';
4
3
  import Model from '../lib/model';
5
4
  import ModelCache from '../lib/model-cache';
6
5
  import {waitsFor} from './test-utils';
@@ -29,7 +28,7 @@ describe('Request', () => {
29
28
  });
30
29
  }
31
30
 
32
- return Promise.resolve([new Model(), '', {response: {status: 200}}]);
31
+ return Promise.resolve([this, {status: 200}]);
33
32
  });
34
33
 
35
34
  jest.spyOn(ModelCache, 'put');
@@ -54,7 +53,7 @@ describe('Request', () => {
54
53
  describe('when using the default exported function', () => {
55
54
  it('returns a promise if the model does not exist', async() => {
56
55
  var model,
57
- promise = request('foo', Model, {component}).then(([_model]) => {
56
+ promise = request('foo', Model, {options: {one: 1}, component}).then(([_model]) => {
58
57
  model = _model;
59
58
  });
60
59
 
@@ -63,6 +62,8 @@ describe('Request', () => {
63
62
  expect(promise instanceof Promise).toBe(true);
64
63
  // in this instance we're resolving immediately, so model should be Model
65
64
  expect(model instanceof Model).toBe(true);
65
+ // this tests that it properly passes along the options object to the model constructor
66
+ expect(model.urlOptions).toEqual({one: 1});
66
67
  });
67
68
 
68
69
  describe('if the model does exist', () => {
@@ -303,15 +304,6 @@ describe('Request', () => {
303
304
  expect(getFromCache('bar')).not.toBeDefined();
304
305
  });
305
306
  });
306
-
307
- describe('getFirstArgPropertyName', () => {
308
- it('returns \'models\' for a collection, \'attributes\' for a model', () => {
309
- class _Collection extends Collection {}
310
- class _Model extends Model {}
311
- expect(getFirstArgPropertyName(_Collection)).toEqual('models');
312
- expect(getFirstArgPropertyName(_Model)).toEqual('attributes');
313
- });
314
- });
315
307
  });
316
308
 
317
309
  /**
package/test/sync.test.js CHANGED
@@ -35,60 +35,94 @@ describe('sync', () => {
35
35
 
36
36
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
37
37
  expect(window.fetch.mock.calls[0][1].method).toEqual('GET');
38
- expect(window.fetch.mock.calls[0][1].data).not.toBeDefined();
38
+ expect(window.fetch.mock.calls[0][1].params).not.toBeDefined();
39
39
  window.fetch.mockClear();
40
40
 
41
- await library.fetch({data: {one: 'two'}});
41
+ await library.fetch({params: {one: 'two'}});
42
42
  expect(window.fetch.mock.calls[0][0]).toEqual('/library?one=two');
43
43
  expect(window.fetch.mock.calls[0][1].method).toEqual('GET');
44
- expect(window.fetch.mock.calls[0][1].data).toEqual({one: 'two'});
44
+ expect(window.fetch.mock.calls[0][1].params).toEqual({one: 'two'});
45
45
  window.fetch.mockClear();
46
46
 
47
- await library.fetch({url: '/library?one=two', data: {two: 'three'}});
47
+ await library.fetch({url: '/library?one=two', params: {two: 'three'}});
48
48
  expect(window.fetch.mock.calls[0][0]).toEqual('/library?one=two&two=three');
49
49
  expect(window.fetch.mock.calls[0][1].method).toEqual('GET');
50
- expect(window.fetch.mock.calls[0][1].data).toEqual({two: 'three'});
50
+ expect(window.fetch.mock.calls[0][1].params).toEqual({two: 'three'});
51
51
  window.fetch.mockClear();
52
52
 
53
53
  // safe call with no options, even though this won't work
54
54
  expect(async() => sync(library)).not.toThrow();
55
55
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
56
56
  expect(window.fetch.mock.calls[0][1].method).not.toBeDefined();
57
- expect(window.fetch.mock.calls[0][1].data).not.toBeDefined();
57
+ expect(window.fetch.mock.calls[0][1].params).not.toBeDefined();
58
58
  });
59
59
 
60
- it('passing data', async() => {
60
+ it('passing params', async() => {
61
61
  // GET
62
- await library.fetch({data: {a: 'a', one: 1}});
62
+ await library.fetch({params: {a: 'a', one: 1}});
63
63
 
64
64
  expect(window.fetch.mock.calls[0][0]).toEqual('/library?a=a&one=1');
65
65
  window.fetch.mockClear();
66
66
 
67
67
  // with body content: already stringified
68
- await library.add(attrs).at(0).save(null, {data: 'somestring'});
68
+ await library.add(attrs).at(0).save(null, {params: 'somestring'});
69
69
 
70
70
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
71
71
  expect(window.fetch.mock.calls[0][1].body).toEqual('somestring');
72
72
  window.fetch.mockClear();
73
73
 
74
74
  // with body content: as JSON
75
- await library.at(0).save(null, {data: {a: 'a', one: 1}});
75
+ await library.at(0).save(null, {params: {a: 'a', one: 1}});
76
76
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
77
77
  expect(window.fetch.mock.calls[0][1].body).toEqual(JSON.stringify({a: 'a', one: 1}));
78
78
  window.fetch.mockClear();
79
79
 
80
80
  // with body content: not as json
81
- await library.at(0).save(null, {data: {a: 'a', one: 1}, contentType: 'resourcerer/json'});
81
+ await library.at(0).save(null, {params: {a: 'a', one: 1}, contentType: 'resourcerer/json'});
82
82
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
83
83
  expect(window.fetch.mock.calls[0][1].body).toEqual('a=a&one=1');
84
84
  });
85
85
 
86
+ it('passes urlOptions to the model to formulate the url path', async() => {
87
+ var librarySectionBook;
88
+
89
+ class LibrarySection extends Collection {
90
+ url({section}) {
91
+ return `/library/${section}`;
92
+ }
93
+ }
94
+
95
+ class LibrarySectionBook extends Model {
96
+ url({section, bookId}) {
97
+ return `/library/${section}/${bookId}`;
98
+ }
99
+ }
100
+
101
+ library = new LibrarySection([], {section: 'nature'});
102
+ await library.fetch({params: {a: 'a', one: 1}});
103
+
104
+ expect(window.fetch.mock.calls[0][0]).toEqual('/library/nature?a=a&one=1');
105
+ // safe
106
+ library = new LibrarySection();
107
+ await library.fetch({params: {a: 'a', one: 1}});
108
+ expect(window.fetch.mock.calls[1][0]).toEqual('/library/undefined?a=a&one=1');
109
+
110
+ librarySectionBook = new LibrarySectionBook({}, {section: 'nature', bookId: 'all-about-frogs'});
111
+ await librarySectionBook.fetch({params: {a: 'a', one: 1}});
112
+ expect(window.fetch.mock.calls[2][0]).toEqual('/library/nature/all-about-frogs?a=a&one=1');
113
+
114
+ // safe
115
+ librarySectionBook = new LibrarySectionBook();
116
+ await librarySectionBook.fetch({params: {a: 'a', one: 1}});
117
+ expect(window.fetch.mock.calls[3][0]).toEqual('/library/undefined/undefined?a=a&one=1');
118
+ });
119
+
86
120
  it('create', async() => {
87
121
  await library.create(attrs, {wait: false});
88
122
 
89
123
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
90
124
  expect(window.fetch.mock.calls[0][1].method).toEqual('POST');
91
- expect(window.fetch.mock.calls[0][1].data).toEqual({
125
+ expect(window.fetch.mock.calls[0][1].params).toEqual({
92
126
  title: 'The Tempest',
93
127
  author: 'Bill Shakespeare',
94
128
  length: 123
@@ -101,7 +135,7 @@ describe('sync', () => {
101
135
 
102
136
  expect(window.fetch.mock.calls[0][0]).toEqual('/library/1-the-tempest');
103
137
  expect(window.fetch.mock.calls[0][1].method).toEqual('PUT');
104
- expect(window.fetch.mock.calls[0][1].data).toEqual({
138
+ expect(window.fetch.mock.calls[0][1].params).toEqual({
105
139
  id: '1-the-tempest',
106
140
  title: 'The Tempest',
107
141
  author: 'William Shakespeare',
@@ -116,7 +150,7 @@ describe('sync', () => {
116
150
 
117
151
  expect(window.fetch.mock.calls[1][0]).toEqual('/library/2-the-tempest');
118
152
  expect(window.fetch.mock.calls[1][1].method).toEqual('GET');
119
- expect(window.fetch.mock.calls[1][1].data).not.toBeDefined();
153
+ expect(window.fetch.mock.calls[1][1].params).not.toBeDefined();
120
154
  });
121
155
 
122
156
  it('destroy', async() => {
@@ -126,7 +160,7 @@ describe('sync', () => {
126
160
 
127
161
  expect(window.fetch.mock.calls[1][0]).toEqual('/library/2-the-tempest');
128
162
  expect(window.fetch.mock.calls[1][1].method).toEqual('DELETE');
129
- expect(window.fetch.mock.calls[1][1].data).not.toBeDefined();
163
+ expect(window.fetch.mock.calls[1][1].params).not.toBeDefined();
130
164
  });
131
165
 
132
166
  it('rejects non-2xx', async() => {
@@ -29,83 +29,3 @@ export function waitsFor(condition, time=3000, name='something to happen') {
29
29
  }, 0);
30
30
  });
31
31
  }
32
-
33
- /**
34
- * Returns reference the wrapped DataCarrier instance, which is in charge of
35
- * keeping loading states as state and passing down our models from the model
36
- * cache into the data child.
37
- *
38
- * @param {object} tree - the top node returned from a withResources declaration
39
- * @return {object} the wrapped DataCarrier instance
40
- */
41
- export function findDataCarrier(tree) {
42
- wrapperCheck(tree);
43
-
44
- return findChildAtDepth(tree, 1);
45
- }
46
-
47
- /**
48
- * Returns reference the wrapped DataChild instance, which is the user-defined
49
- * component that gets the @withResources decorator attached to it.
50
- *
51
- * @param {object} tree - the top node returned from a withResources declaration
52
- * @return {object} the wrapped DataChild instance
53
- */
54
- export function findDataChild(tree) {
55
- wrapperCheck(tree);
56
-
57
- return findChildAtDepth(tree, 3);
58
- }
59
-
60
- /**
61
- * Return an object with reference all wrapped children returned within a
62
- * withResources declaration instance.
63
- *
64
- * @param {object} tree - the top node returned from a withResources declaration
65
- * @return {object} an object containing references to the parent resources
66
- * component, the data carrier, data child, and even the error boundary
67
- * component instances.
68
- */
69
- export function getRenderedResourceComponents(tree) {
70
- wrapperCheck(tree);
71
-
72
- return {
73
- resources: tree,
74
- dataCarrier: findDataCarrier(tree),
75
- dataChild: findDataChild(tree),
76
- errorBoundary: findChildAtDepth(tree, 2)
77
- };
78
- }
79
-
80
- /**
81
- * In order for the wrapped-component convenience methods to work, the argument
82
- * must be an instance of ResourceStateWrapper returned from a `withResources`
83
- * declaration. This check throws an error if that is not the case.
84
- *
85
- * @param {object} tree - the top node for which to verify its type
86
- */
87
- function wrapperCheck(tree) {
88
- if (Object.getPrototypeOf(tree).constructor.name !== 'ResourceStateWrapper') {
89
- throw new Error('Component must be of type returned by withResources function');
90
- }
91
- }
92
-
93
- /**
94
- * Core to our wrapped-component convenience methods, we simply walk down the
95
- * React tree a specified depth, which we know to always be true for our
96
- * wrapped components. This is all-the-easier because there are no siblings to
97
- * crawl.
98
- *
99
- * @param {object} node - entry in the React render tree
100
- * @param {number} depth - number of entries to crawl to get the child of interest
101
- * @return {object} rendered instance of wrapped component
102
- */
103
- function findChildAtDepth(node, depth=0) {
104
- var i = 0;
105
-
106
- while (i++ < depth) {
107
- node = node.child || node._reactInternalFiber.child;
108
- }
109
-
110
- return node.stateNode;
111
- }
@@ -190,6 +190,7 @@ describe('Utils', () => {
190
190
  describe('result', () => {
191
191
  it('returns the correct value if a function', () => {
192
192
  expect(result({foo: () => 'bar'}, 'foo')).toEqual('bar');
193
+ expect(result({foo: (x, y) => x + y + 5}, 'foo', 10, 5)).toEqual(20);
193
194
  });
194
195
 
195
196
  it('returns the correct value if not a function', () => {