resourcerer 1.0.12 → 1.1.0

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/index.d.ts ADDED
@@ -0,0 +1,245 @@
1
+ // this will make CONST_CASE a camelCase but also leave camelCase alone
2
+ type Camelize<T extends string> = T extends `${infer A}_${infer B}` ?
3
+ `${Lowercase<A>}${Camelize<Capitalize<B>>}` :
4
+ T extends Uppercase<T> ?
5
+ Capitalize<Lowercase<T>> :
6
+ T extends `${infer A}${Uppercase<infer B>}` ?
7
+ Lowercase<T> :
8
+ T;
9
+
10
+ declare module 'resourcerer' {
11
+ type SyncOptions = {
12
+ attrs?: Record<string, any>;
13
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
14
+ params?: Record<string, any>;
15
+ url?: string;
16
+ };
17
+
18
+ type SetOptions = {
19
+ silent?: boolean;
20
+ unset?: boolean;
21
+ };
22
+
23
+ // for collection.set
24
+ type CSetOptions = {
25
+ parse?: boolean;
26
+ silent?: boolean;
27
+ };
28
+
29
+ declare class Model<T extends Record<string, any> = {[key: string]: any}> {
30
+ constructor(attrs?: T, options?: Record<string, any> & SetOptions): Model;
31
+
32
+ // TODO: need to reference idAttribute here
33
+ id: T extends {id: string} ? string : string | undefined;
34
+
35
+ get<K extends keyof T>(key: K): T[K];
36
+
37
+ has(key: keyof T): boolean;
38
+
39
+ clear(options?: SetOptions): Model;
40
+
41
+ unset(attr: keyof T, options?: SetOptions): Model;
42
+
43
+ parse(response: Record<string, any>): T;
44
+
45
+ pick<K extends keyof T>(...attrs: K[]): Pick<T, K>;
46
+
47
+ set(attrs: Partial<T>, options?: SetOptions): Model;
48
+
49
+ fetch(options?: {parse?: boolean} & SyncOptions & SetOptions): Promise<[Model, Response]>;
50
+
51
+ save(attrs: Partial<T>, options?: {wait?: boolean} & SyncOptions & SetOptions):
52
+ Promise<[Model, Response]>;
53
+
54
+ destroy(options?: {wait?: boolean} & SyncOptions & SetOptions): Promise<[Model, Response]>;
55
+
56
+ isNew(): boolean;
57
+
58
+ toJSON(): T;
59
+
60
+ url(): string;
61
+
62
+ urlRoot(): string;
63
+
64
+ static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
65
+
66
+ static cacheTimeout: number;
67
+
68
+ static idAttribute: string;
69
+
70
+ static defaults: Record<keyof T, any> | (() => Record<keyof T, any>);
71
+
72
+ static measure: boolean | (() => void);
73
+ }
74
+
75
+ type ModelArg<A> = Model<A> | Record<string, any>;
76
+
77
+ declare class Collection<
78
+ T extends Record<string, any> = {[key: string]: any},
79
+ O extends Record<string, any> & CSetOptions = {[key: string]: any}
80
+ > {
81
+ constructor(
82
+ models?: ModelArg<T> | ModelArg<T>[],
83
+ options?: O
84
+ ): Collection;
85
+
86
+ length: number;
87
+
88
+ add(models: ModelArg<T> | ModelArg<T>[], options: CSetOptions): Collection;
89
+
90
+ remove(models: ModelArg<T> | ModelArg<T>[]): Collection;
91
+
92
+ set(models: ModelArg<T> | ModelArg<T>[], options: CSetOptions): Collection;
93
+
94
+ reset(models: ModelArg<T>[], options: CSetOptions): Collection;
95
+
96
+ get(id?: string | ModelArg<T>): Model<T> | undefined;
97
+
98
+ has(id?: string | ModelArg<T>): boolean;
99
+
100
+ at(index: number): Model<T> | undefined;
101
+
102
+ toJSON(): T[];
103
+
104
+ sort(): Collection;
105
+
106
+ map<R = any>(predicate: (model: Model<T>) => R): R[];
107
+
108
+ find(predicate: (model: Model<T>) => boolean): Model<T>;
109
+
110
+ filter(predicate: (model: Model<T>) => boolean): Model<T>[];
111
+
112
+ findWhere<K extends keyof T>(attrs: Record<K, T[K]>): Model<T>;
113
+
114
+ where<K extends keyof T, B extends boolean = false>(attrs: Record<K, T[K]>, find?: B):
115
+ B extends true ?
116
+ Model<T> :
117
+ Model<T>[];
118
+
119
+ pluck<K extends keyof T>(prop: K): Record<K, T[K]>[];
120
+
121
+ slice(start: number, end?: number): ModelArg<T>[];
122
+
123
+ parse(response: Record<string, any> | any[], options?: Record<string, any>): Array<T>;
124
+
125
+ create(
126
+ model: ModelArg<T>,
127
+ options?: {wait?: boolean} & SyncOptions & CSetOptions
128
+ ): Promise<[Collection, Response]>;
129
+
130
+ fetch(options?: {parse?: boolean} & SyncOptions & CSetOptions): Promise<[Collection, Response]>;
131
+
132
+ url(urlOptions?: O): string;
133
+
134
+ static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
135
+
136
+ static modelIdAttribute: string;
137
+
138
+ static measure: boolean | (() => void);
139
+
140
+ static cacheTimeout: number;
141
+
142
+ static comparator: string |
143
+ ((arg: Model<T>) => number | string) |
144
+ ((arg1: Model<T>, arg2: Model<T>) => number);
145
+ }
146
+
147
+ type LoadingTypes = 'loading' | 'loaded' | 'errored' | 'pending';
148
+
149
+ // this will be filled out by users
150
+ export interface ModelMap {}
151
+
152
+ type ResourceKeys = {
153
+ [key in keyof ModelMap]: key extends string ? Camelize<Uncapitalize<key>> : key
154
+ }
155
+
156
+ type ModelProperty<Str extends string> = {[key: `${Str}Model`]: Model};
157
+ type CollectionProperty<Str extends string> = {[key: `${Str}Collection`]: Collection};
158
+
159
+ interface UseResourcesResponse {
160
+ isLoading: boolean;
161
+ hasErrored: boolean;
162
+ hasLoaded: boolean;
163
+ hasInitiallyLoaded: boolean;
164
+ refetch: (fn: (keys: {[key: string]: ResourceKeys}) => ResourceKeys[]) => void;
165
+ setResourceState(newState: {[key: string]: any}): void;
166
+ isOrWillBeLoading(): boolean;
167
+ [key: `${string}LoadingState`]: LoadingTypes;
168
+ }
169
+
170
+ declare function haveAllLoaded(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
171
+ declare function haveAnyErrored(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
172
+ declare function areAnyLoading(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
173
+ declare function areAnyPending(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
174
+
175
+ type ResourceConfigObj = {
176
+ data?: {[key: string]: any};
177
+ dependsOn?: string[];
178
+ force?: boolean;
179
+ lazy?: boolean;
180
+ modelKey?: ResourceKeys;
181
+ noncritical?: boolean;
182
+ options?: {[key: string]: any};
183
+ params?: {[key: string]: any};
184
+ prefetches?: {[key: string]: any}[];
185
+ provides?: (model: Model | Collection) => {[key: string]: any};
186
+ };
187
+
188
+ type ResourceValues = Extract<typeof ResourceKeys[keyof typeof ResourceKeys], string>;
189
+ type InvertedResourceKeys = {[Key in keyof ResourceKeys as ResourceKeys[Key]]: Key};
190
+
191
+ // TODO: how to only use those keys that were passed, not the whole resourcekeys obj
192
+ export type ExecutorFunction = (
193
+ ResourceKeys_: ResourceKeys,
194
+ props: {[key: string]: any}
195
+ ) => Partial<Record<ResourceValues, ResourceConfigObj>>;
196
+
197
+ type WithModelSuffix<K, C> = C extends Collection ? `${K}Collection` : `${K}Model`;
198
+
199
+ declare function useResources(
200
+ getResources: ExecutorFunction,
201
+ props: {[key: string]: any}
202
+ ): UseResourcesResponse & {
203
+ [Key in keyof Required<ReturnType<ExecutorFunction>> as
204
+ WithModelSuffix<Key, InstanceType<ModelMap[InvertedResourceKeys[Key]]>>]:
205
+ InstanceType<ModelMap[InvertedResourceKeys[Key]]>
206
+ };
207
+
208
+ type test = ReturnType<ExecutorFunction>;
209
+
210
+ export interface ModelCache {
211
+ get(key: string): Model | Collection | undefined;
212
+ put(key: string, model: Model | Collection, component: any): void;
213
+ register(key: string, component: any): void;
214
+ unregister(component: any, ...keys: string[]): void;
215
+ remove(key: string): void;
216
+ __removeAll__(): void;
217
+ }
218
+
219
+ interface TrackOptions {
220
+ Resource: string;
221
+ params: {[key: string]: any};
222
+ options: {[key: string]: any};
223
+ duration: number;
224
+ }
225
+
226
+ interface RequestPrefilter {
227
+ // TODO
228
+ error: (...args: any[]) => any;
229
+ headers: {[key: string]: string};
230
+ }
231
+
232
+ type ResourcerConfigOptions = {
233
+ cacheGracePeriod?: number;
234
+ errorBoundaryChild?: any;
235
+ log?: (err: Error) => void;
236
+ queryParamsPropName?: string;
237
+ stringify?: (params: {[key: string]: any}, options: {[key: string]: any}) => string;
238
+ track?: (name: string, options: TrackOptions) => void;
239
+ prefilter?: (options: {[key: string]: any}) => RequestPrefilter;
240
+ };
241
+
242
+ let ResourceKeys: ResourceKeys & {add(keys: Partial<ResourceKeys>): void;};
243
+ let ResourcesConfig: ResourcerConfigOptions & {set: (options: ResourcerConfigOptions) => void;};
244
+ let ModelMap: ModelMap & {add(keys: ModelMap): void;};
245
+ }
@@ -113,9 +113,10 @@ export default {
113
113
  * @param {string} cacheKey - The cache key of the model to be removed.
114
114
  */
115
115
  function scheduleForRemoval(cacheKey) {
116
- timeouts[cacheKey] = window.setTimeout(() => {
117
- clearModel(cacheKey);
118
- }, ResourcesConfig.cacheGracePeriod);
116
+ var timeout = modelCache.get(cacheKey)?.constructor.cacheTimeout ||
117
+ ResourcesConfig.cacheGracePeriod;
118
+
119
+ timeouts[cacheKey] = window.setTimeout(() => clearModel(cacheKey), timeout);
119
120
  }
120
121
 
121
122
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.0.12",
3
+ "version": "1.1.0",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": [
@@ -9,9 +9,11 @@
9
9
  ],
10
10
  "files": [
11
11
  "*.js",
12
+ "index.d.ts",
12
13
  "lib/*.js",
13
14
  "test/*.js",
14
- "*.md"
15
+ "*.md",
16
+ "docs/*.md"
15
17
  ],
16
18
  "main": "index.js",
17
19
  "scripts": {
@@ -1,3 +1,5 @@
1
+ import Collection from '../lib/collection';
2
+ import Model from '../lib/model';
1
3
  import ModelCache from '../lib/model-cache';
2
4
 
3
5
  const CACHE_WAIT = 150000,
@@ -51,6 +53,31 @@ describe('ModelCache', () => {
51
53
  jest.advanceTimersByTime(CACHE_WAIT);
52
54
  expect(ModelCache.get(PUT_KEY)).not.toBeDefined();
53
55
  });
56
+
57
+ it('uses a model-specific timeout if available', () => {
58
+ class TimeoutModel extends Model {
59
+ static cacheTimeout = 3000;
60
+ }
61
+
62
+ class TimeoutCollection extends Collection {
63
+ static cacheTimeout = CACHE_WAIT + 2000;
64
+ }
65
+
66
+ jest.advanceTimersByTime(CACHE_WAIT);
67
+ expect(ModelCache.get(PUT_KEY)).not.toBeDefined();
68
+
69
+ ModelCache.put(PUT_KEY, new TimeoutModel());
70
+ jest.advanceTimersByTime(2000);
71
+ expect(ModelCache.get(PUT_KEY)).toBeDefined();
72
+ jest.advanceTimersByTime(2000);
73
+ expect(ModelCache.get(PUT_KEY)).not.toBeDefined();
74
+
75
+ ModelCache.put(PUT_KEY, new TimeoutCollection());
76
+ jest.advanceTimersByTime(CACHE_WAIT);
77
+ expect(ModelCache.get(PUT_KEY)).toBeDefined();
78
+ jest.advanceTimersByTime(2000);
79
+ expect(ModelCache.get(PUT_KEY)).not.toBeDefined();
80
+ });
54
81
  });
55
82
  });
56
83