resourcerer 1.2.3 → 2.0.0-beta

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 +68 -20
  33. package/package.json +27 -30
  34. package/resourcerer.d.ts +50 -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
package/lib/sync.js DELETED
@@ -1,111 +0,0 @@
1
- import {result, urlError} from './utils.js';
2
-
3
- import {ResourcesConfig} from './config.js';
4
-
5
- const MIME_TYPE_JSON = 'application/json';
6
-
7
- var prefilter = (x) => x;
8
-
9
- /**
10
- * The basic sync function, which does very little other than prep the options argument sent to the
11
- * ajax function. It basically sets up defaults, seeding the query params if not explicitly
12
- * specified already. It also finds the base url or throws if one does not exist.
13
- *
14
- * @param {Model|Collection} model - model making API request
15
- * @param {object} options - generic map of request options
16
- * @return {promise} fetch request. resolves with an array of the model and its request status or
17
- * rejects with the response
18
- */
19
- export default function(model, options={}) {
20
- return ajax({
21
- contentType: MIME_TYPE_JSON,
22
- // url can be passed via the model (as a property or function) or via options.url directly
23
- ...!options.url ? {url: result(model, 'url', model.urlOptions) || urlError()} : {},
24
- ...!options.params && ['POST', 'PATCH', 'PUT'].includes(options.method) ?
25
- {params: options.attrs || model.toJSON()} :
26
- {},
27
- // default catch block. most large applications should override this in the config settings to
28
- // provide support for things like 401s or 429s.
29
- error: (response) => Promise.reject(response),
30
- ...options
31
- });
32
- }
33
-
34
- /**
35
- * This is the method that actually makes the fetch call. It also runs the prefilter set up in the
36
- * config to modify any request options before the fetch takes place.
37
- *
38
- * @param {object} options - map of request options:
39
- * * url {string} - this is required, but will be present automatically if not passed directly in
40
- * the sync method's request object
41
- * * params {object} - will be url-stringified for GET requests and JSON-stringified for POST
42
- * bodies
43
- * * headers {object} - map of headers to their values
44
- * * contentType {string} value of content type header, which will also determine how the POST
45
- * bodies are assembled
46
- * * error {function} - rejected promise callback, called with the request Response object. this
47
- * should be customized for most large applications
48
- * @return {promise} fetch request. resolves with an array of the model and its request status or
49
- * rejects with the response
50
- */
51
- export function ajax(options) {
52
- var hasParams = !!Object.keys(options.params || {}).length,
53
- hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams,
54
- startTime = Date.now(),
55
- onRequestComplete = (json, response) => {
56
- var requestDuration = Date.now() - startTime,
57
- routeRequest = (
58
- resolve=Promise.resolve.bind(Promise),
59
- reject=Promise.reject.bind(Promise)
60
- ) => response.ok ?
61
- resolve([json, response]) :
62
- reject(Object.assign(response, {json}));
63
-
64
- return !options.minDuration || requestDuration >= options.minDuration ?
65
- routeRequest() :
66
- new Promise((resolve, reject) => window.setTimeout(
67
- () => routeRequest(resolve, reject),
68
- options.minDuration - requestDuration
69
- ));
70
- };
71
-
72
- if (options.method === 'GET' && hasParams) {
73
- options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
74
- ResourcesConfig.stringify(options.params, options);
75
- }
76
-
77
- options = {...options, ...prefilter(options)};
78
-
79
- return window.fetch(options.url, {
80
- ...options,
81
- headers: {
82
- Accept: MIME_TYPE_JSON,
83
- // only set contentType header if a write request and if there is body params. also, default
84
- // to JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
85
- ...hasBodyContent ? {'Content-Type': options.contentType} : {},
86
- ...options.headers
87
- },
88
- ...hasBodyContent ? {
89
- body: typeof options.params === 'string' ?
90
- options.params :
91
- options.contentType === MIME_TYPE_JSON ?
92
- JSON.stringify(options.params) :
93
- ResourcesConfig.stringify(options.params, options)
94
- } : {}
95
- // catch block here handles the case where the response isn't valid json,
96
- // like for example a 204 no content
97
- }).then(
98
- (res) => res.json()
99
- .catch(() => ({}))
100
- .then((json) => onRequestComplete(json, res))
101
- ).catch(options.error);
102
- }
103
-
104
- /**
105
- * Override this to provide custom request options manipulation before a request
106
- * goes out, for example, to add auth headers to the `headers` property, or to
107
- * custom wrap the error callback in the `error` property.
108
- */
109
- export function setRequestPrefilter(_prefilter) {
110
- prefilter = _prefilter;
111
- }
package/lib/utils.js DELETED
@@ -1,220 +0,0 @@
1
- import {LoadingStates} from './constants.js';
2
-
3
- /**
4
- * Whether or not any loading state has errored. If a state is passed in,
5
- * check only that one, else we check for any.
6
- *
7
- * @param {string|string[]|object} loadingStates - specifics state to check for an error
8
- * @return {boolean}
9
- */
10
- export const hasErrored = (loadingStates) =>
11
- qualifyLoadingStates(loadingStates).some((state) => state === LoadingStates.ERROR);
12
-
13
- /**
14
- * Whether or not any render-blocking loading state is still loading. If a
15
- * state is passed in, check only that one, else we check for any.
16
- *
17
- * @param {string|string[]|object} loadingStates - specific states to check if one is loading
18
- * @return {boolean}
19
- */
20
- export const isLoading = (loadingStates) =>
21
- qualifyLoadingStates(loadingStates).some((state) => state === LoadingStates.LOADING);
22
-
23
- /**
24
- * Whether or not all render-blocking loading states have loaded. If a
25
- * state is passed in, check only that one, else we check for all.
26
- *
27
- * @param {string|string[]|object} loadingStates - specific states to check that all have loaded
28
- * @return {boolean}
29
- */
30
- export const hasLoaded = (loadingStates) =>
31
- qualifyLoadingStates(loadingStates).every((state) => state === LoadingStates.LOADED);
32
-
33
- /**
34
- * Whether or not any loading state is pending. If a state is passed in,
35
- * check only that one, else we check for any.
36
- *
37
- * @param {string|string[]|object} loadingStates - specifics state to check for an error
38
- * @return {boolean}
39
- */
40
- export const isPending = (loadingStates) =>
41
- qualifyLoadingStates(loadingStates).some((state) => state === LoadingStates.PENDING);
42
-
43
- export function noOp() {}
44
-
45
- /**
46
- * Turns a snake-, spine-, or space-cased word into camelCase. Used to turn
47
- * resource keys (as input by the model map) into strings for prop prefixing.
48
- *
49
- * @param {string} word - string to camelcase
50
- * @return {string} camelCased word
51
- */
52
- export function camelize(word='') {
53
- const SPACERS = /[-_\s]+(.)?/g;
54
-
55
- // let words that are already camelCase pass, but still catch SINGLE WORD ALL CAPS
56
- if (!SPACERS.test(word) && word.toUpperCase() !== word) {
57
- return word;
58
- }
59
-
60
- return word.trim().toLowerCase().replace(SPACERS, (match, char) => char?.toUpperCase());
61
- }
62
-
63
- /**
64
- * @param {function} fn - method to invoke only once
65
- * @return {function} function, that, after getting invoked once, gets set to null
66
- */
67
- export function once(fn) {
68
- return (...args) => {
69
- if (fn) {
70
- fn.call(null, ...args);
71
- fn = null;
72
- }
73
- };
74
- }
75
-
76
- /**
77
- * Returns a new object with only those properties listed in keys.
78
- *
79
- * @param {object} obj - object to pick properties from
80
- * @param {string[]} keys - list of keys to pick from obj
81
- * @return {object} new object with only those properties listed
82
- */
83
- export function pick(obj={}, ...keys) {
84
- return keys.reduce((memo, key) => {
85
- if (obj.hasOwnProperty(key)) {
86
- memo[key] = obj[key];
87
- }
88
-
89
- return memo;
90
- }, {});
91
- }
92
-
93
- /**
94
- * Inverse of pick; returns a new object with all properties _except_ those listed in keys.
95
- *
96
- * @param {object} obj - object to omit properties from
97
- * @param {string[]} keys - list of keys to omit from obj
98
- * @return {object} new object with only those properties not listed in keys
99
- */
100
- export function omit(obj={}, ...keys) {
101
- return pick(obj, ...Object.keys(obj).filter((key) => !keys.includes(key)));
102
- }
103
-
104
- /**
105
- * Our helper loading methods can take many types: a single loading state, an
106
- * array of loading states, or an object whose values are loading states. This
107
- * method takes the different shapes and returns an array of loading state
108
- * values to be processed by the rest of the helper methods.
109
- *
110
- * @param {string|string[]|object} loadingStates - specific states to transform into an array
111
- * @return {string[]} - list of LoadingState values
112
- */
113
- function qualifyLoadingStates(loadingStates) {
114
- if (!Array.isArray(loadingStates)) {
115
- if (loadingStates && typeof loadingStates === 'object') {
116
- return Object.values(loadingStates);
117
- }
118
-
119
- return [loadingStates];
120
- }
121
-
122
- return loadingStates;
123
- }
124
-
125
- /**
126
- * Function that returns an optionally-prefixed unique value every time it's called (unpersisted,
127
- * of course).
128
- *
129
- * @return {function}
130
- */
131
- export const uniqueId = (() => {
132
- var count = 0;
133
-
134
- return (prefix='') => {
135
- count++;
136
-
137
- return `${prefix}${count}`;
138
- };
139
- })();
140
-
141
- /**
142
- * Used to throw when a url function or property has not been specified on a Model or Collection.
143
- */
144
- export function urlError() {
145
- throw new Error('A "url" property or function must be specified');
146
- }
147
-
148
- /**
149
- * Does a nested comparison between two objects to determine whether or not they are equivalent by
150
- * value.
151
- *
152
- * @param {object} obj1 - first object to compare
153
- * @param {object} obj2 - second object to compare
154
- * @return {boolean} whether the two objects are equivalent by value
155
- */
156
- export function isDeepEqual(obj1, obj2) {
157
- if (obj1 === obj2) {
158
- return true;
159
- } else if ((typeof obj1 === 'object' && obj1 !== null) &&
160
- (typeof obj2 === 'object' && obj2 !== null)) {
161
- if (Object.keys(obj1).length !== Object.keys(obj2).length) {
162
- return false;
163
- }
164
-
165
- for (let prop in obj1) {
166
- if (obj2.hasOwnProperty(prop)) {
167
- if (!isDeepEqual(obj1[prop], obj2[prop])) {
168
- return false;
169
- }
170
- } else {
171
- return false;
172
- }
173
- }
174
-
175
- return true;
176
- }
177
-
178
- return false;
179
- }
180
-
181
- /**
182
- * Sorting function that mirrors the underscore version. This is used by collections with comparator
183
- * properties.
184
- *
185
- * @param {any[]} list - list of items to sort
186
- * @param {function} comparator - takes the list item and should return a value to compare with
187
- * other items in the list
188
- * @param {any[]} - sorted list
189
- */
190
- export function sortBy(list=[], comparator) {
191
- /* eslint-disable id-length */
192
- return list.map((value, index) => ({value, index, criteria: comparator(value)}))
193
- .sort((left, right) => {
194
- var a = left.criteria,
195
- b = right.criteria;
196
-
197
- if (a !== b) {
198
- if (a > b || a === undefined) {
199
- return 1;
200
- } else if (a < b || b === undefined) {
201
- return -1;
202
- }
203
- }
204
-
205
- return left.index - right.index;
206
- })
207
- .map(({value}) => value);
208
- /* eslint-enable id-length */
209
- }
210
-
211
- /**
212
- * Helper method for those properties that can optionally be functions.
213
- *
214
- * @param {object} obj - parent object of which to find property value
215
- * @param {any} prop - property of object to evaluate
216
- * @return {any} evaluated value of object at property
217
- */
218
- export function result(obj={}, prop, ...args) {
219
- return typeof obj[prop] === 'function' ? obj[prop](...args) : obj[prop];
220
- }
@@ -1,110 +0,0 @@
1
- import Collection from '../lib/collection';
2
- import Model from '../lib/model';
3
-
4
- export class UserModel extends Model {
5
- key = 'user'
6
-
7
- constructor(attributes, options={}) {
8
- super(attributes, options);
9
-
10
- this.userId = options.userId;
11
- }
12
-
13
- url() {
14
- return `/root/users/${this.userId}`;
15
- }
16
-
17
- static dependencies = ['fraudLevel', 'userId', 'id']
18
- }
19
-
20
- export class AnalystsCollection extends Collection {
21
- key = 'analysts'
22
-
23
- url() {
24
- return '/root/analysts';
25
- }
26
- }
27
-
28
- export class DecisionsCollection extends Collection {
29
- key = 'decisions'
30
-
31
- url() {
32
- return '/root/decisions';
33
- }
34
-
35
- static cacheFields = ['include_deleted']
36
- }
37
-
38
- export class NotesModel extends Model {
39
- key = 'notes'
40
-
41
- url({userId}) {
42
- return `/root/${userId}/notes`;
43
- }
44
-
45
- static cacheFields = ['userId']
46
- }
47
-
48
- export class SearchQueryModel extends Model {
49
- key = 'search'
50
-
51
- fetch(options={}) {
52
- options = {
53
- ...options,
54
- contentType: 'application/json',
55
- params: JSON.stringify(options.params),
56
- type: 'POST'
57
- };
58
-
59
- return Model.prototype.fetch.call(this, options);
60
- }
61
-
62
- url() {
63
- return '/root/search';
64
- }
65
-
66
- static dependencies = ['type', 'detailed', 'filter', 'sort', 'limit', 'from']
67
- }
68
-
69
- export class SignalsCollection extends Collection {
70
- key = 'signals'
71
-
72
- url() {
73
- return '/root/signals';
74
- }
75
- }
76
-
77
- export class ActionsCollection extends Collection {
78
- key = 'actions'
79
-
80
- url() {
81
- return '/root/actions';
82
- }
83
- }
84
-
85
- export class DecisionLogsCollection extends Collection {
86
- key = 'decisionLogs'
87
-
88
- url() {
89
- return '/root/decision_logs';
90
- }
91
-
92
- static cacheFields = ['logs']
93
- }
94
-
95
- // next three are unfetched resources
96
- export class DecisionInstanceModel extends Model {
97
- static dependencies = ['entityType', 'entityId']
98
- }
99
-
100
- export class LabelInstanceModel extends Model {
101
- static dependencies = ['userId']
102
- }
103
-
104
- export class AccountConfigModel extends Model {
105
- key = 'accountConfig'
106
-
107
- url({accountId}) {
108
- return `/root/accounts/${accountId}/config`;
109
- }
110
- }
package/test/setup.js DELETED
@@ -1,63 +0,0 @@
1
- import 'whatwg-fetch';
2
-
3
- /**
4
- * This file includes all test setup--setup mocked as it would normally be
5
- * mocked within a real app, adding resource keys, models, and unfetched
6
- * resources.
7
- */
8
- import {
9
- AccountConfigModel,
10
- ActionsCollection,
11
- AnalystsCollection,
12
- DecisionInstanceModel,
13
- DecisionLogsCollection,
14
- DecisionsCollection,
15
- LabelInstanceModel,
16
- NotesModel,
17
- SearchQueryModel,
18
- SignalsCollection,
19
- UserModel
20
- } from './model-mocks';
21
- import {ModelMap, ResourceKeys, ResourcesConfig, UnfetchedResources} from '../lib/config';
22
- import React from 'react';
23
-
24
- ResourceKeys.add({
25
- ACCOUNT_CONFIG: 'accountConfig',
26
- ACTIONS: 'actions',
27
- ANALYSTS: 'analysts',
28
- DECISION_LOGS: 'decisionLogs',
29
- DECISION_INSTANCE: 'decisionInstance',
30
- DECISIONS: 'decisions',
31
- LABEL_INSTANCE: 'labelInstance',
32
- NOTES: 'notes',
33
- SEARCH_QUERY: 'searchQuery',
34
- SIGNALS: 'signals',
35
- USER: 'user'
36
- });
37
-
38
- ModelMap.add({
39
- [ResourceKeys.ACCOUNT_CONFIG]: AccountConfigModel,
40
- [ResourceKeys.ACTIONS]: ActionsCollection,
41
- [ResourceKeys.ANALYSTS]: AnalystsCollection,
42
- [ResourceKeys.DECISION_INSTANCE]: DecisionInstanceModel,
43
- [ResourceKeys.DECISION_LOGS]: DecisionLogsCollection,
44
- [ResourceKeys.DECISIONS]: DecisionsCollection,
45
- [ResourceKeys.LABEL_INSTANCE]: LabelInstanceModel,
46
- [ResourceKeys.NOTES]: NotesModel,
47
- [ResourceKeys.SEARCH_QUERY]: SearchQueryModel,
48
- [ResourceKeys.SIGNALS]: SignalsCollection,
49
- [ResourceKeys.USER]: UserModel
50
- });
51
-
52
- UnfetchedResources
53
- .add(ResourceKeys.ACCOUNT_CONFIG)
54
- .add(ResourceKeys.DECISION_INSTANCE)
55
- .add(ResourceKeys.LABEL_INSTANCE);
56
-
57
- class Loader extends React.Component {
58
- render() {
59
- return <div className='Loader' />;
60
- }
61
- }
62
-
63
- ResourcesConfig.set({Loader});