@ember-data/request-utils 5.4.0-alpha.6 → 5.4.0-alpha.60

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
@@ -28,6 +28,16 @@ Install using your javascript package manager of choice. For instance with [pnpm
28
28
  ```no-highlight
29
29
  pnpm add @ember-data/request-utils
30
30
  ```
31
+
32
+ **Tagged Releases**
33
+
34
+ - ![NPM Canary Version](https://img.shields.io/npm/v/%40ember-data/request-utils/canary?label=%40canary&color=FFBF00)
35
+ - ![NPM Beta Version](https://img.shields.io/npm/v/%40ember-data/request-utils/beta?label=%40beta&color=ff00ff)
36
+ - ![NPM Stable Version](https://img.shields.io/npm/v/%40ember-data/request-utils/latest?label=%40latest&color=90EE90)
37
+ - ![NPM LTS Version](https://img.shields.io/npm/v/%40ember-data/request-utils/lts?label=%40lts&color=0096FF)
38
+ - ![NPM LTS 4.12 Version](https://img.shields.io/npm/v/%40ember-data/request-utils/lts-4-12?label=%40lts-4-12&color=bbbbbb)
39
+
40
+
31
41
  ## Utils
32
42
 
33
43
  - [buildBaseUrl]()
package/addon/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { assert } from '@ember/debug';
1
+ import { assert, deprecate } from '@ember/debug';
2
2
 
3
3
  /**
4
4
  * Simple utility function to assist in url building,
@@ -43,18 +43,70 @@ import { assert } from '@ember/debug';
43
43
  // prevents the final constructed object from needing to add
44
44
  // host and namespace which are provided by the final consuming
45
45
  // class to the prototype which can result in overwrite errors
46
- let CONFIG = {
46
+
47
+ const CONFIG = {
47
48
  host: '',
48
49
  namespace: ''
49
50
  };
50
- function setBuildURLConfig(values) {
51
- CONFIG = values;
51
+
52
+ /**
53
+ * Sets the global configuration for `buildBaseURL`
54
+ * for host and namespace values for the application.
55
+ *
56
+ * These values may still be overridden by passing
57
+ * them to buildBaseURL directly.
58
+ *
59
+ * This method may be called as many times as needed.
60
+ * host values of `''` or `'/'` are equivalent.
61
+ *
62
+ * Except for the value of `/` as host, host should not
63
+ * end with `/`.
64
+ *
65
+ * namespace should not start or end with a `/`.
66
+ *
67
+ * ```ts
68
+ * type BuildURLConfig = {
69
+ * host: string;
70
+ * namespace: string'
71
+ * }
72
+ * ```
73
+ *
74
+ * Example:
75
+ *
76
+ * ```ts
77
+ * import { setBuildURLConfig } from '@ember-data/request-utils';
78
+ *
79
+ * setBuildURLConfig({
80
+ * host: 'https://api.example.com',
81
+ * namespace: 'api/v1'
82
+ * });
83
+ * ```
84
+ *
85
+ * @method setBuildURLConfig
86
+ * @static
87
+ * @public
88
+ * @for @ember-data/request-utils
89
+ * @param {BuildURLConfig} config
90
+ * @return void
91
+ */
92
+ function setBuildURLConfig(config) {
93
+ assert(`setBuildURLConfig: You must pass a config object`, config);
94
+ assert(`setBuildURLConfig: You must pass a config object with a 'host' or 'namespace' property`, 'host' in config || 'namespace' in config);
95
+ CONFIG.host = config.host || '';
96
+ CONFIG.namespace = config.namespace || '';
97
+ assert(`buildBaseURL: host must NOT end with '/', received '${CONFIG.host}'`, CONFIG.host === '/' || !CONFIG.host.endsWith('/'));
98
+ assert(`buildBaseURL: namespace must NOT start with '/', received '${CONFIG.namespace}'`, !CONFIG.namespace.startsWith('/'));
99
+ assert(`buildBaseURL: namespace must NOT end with '/', received '${CONFIG.namespace}'`, !CONFIG.namespace.endsWith('/'));
52
100
  }
53
101
  const OPERATIONS_WITH_PRIMARY_RECORDS = new Set(['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord']);
54
102
  function isOperationWithPrimaryRecord(options) {
55
- return OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
103
+ return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
104
+ }
105
+ function hasResourcePath(options) {
106
+ return 'resourcePath' in options && typeof options.resourcePath === 'string' && options.resourcePath.length > 0;
56
107
  }
57
108
  function resourcePathForType(options) {
109
+ assert(`resourcePathForType: You must pass a valid op as part of options`, 'op' in options && typeof options.op === 'string');
58
110
  return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;
59
111
  }
60
112
 
@@ -97,20 +149,20 @@ function resourcePathForType(options) {
97
149
  * @public
98
150
  * @for @ember-data/request-utils
99
151
  * @param urlOptions
100
- * @returns string
152
+ * @return string
101
153
  */
102
154
  function buildBaseURL(urlOptions) {
103
155
  const options = Object.assign({
104
156
  host: CONFIG.host,
105
157
  namespace: CONFIG.namespace
106
158
  }, urlOptions);
107
- assert(`buildBaseURL: You must pass \`op\` as part of options`, typeof options.op === 'string' && options.op.length > 0);
108
- assert(`buildBaseURL: You must pass \`identifier\` as part of options`, options.op === 'findMany' || options.identifier && typeof options.identifier === 'object');
109
- assert(`buildBaseURL: You must pass \`identifiers\` as part of options`, options.op !== 'findMany' || options.identifiers && Array.isArray(options.identifiers) && options.identifiers.length > 0 && options.identifiers.every(i => i && typeof i === 'object'));
110
- assert(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'id'`, !isOperationWithPrimaryRecord(options) || typeof options.identifier.id === 'string' && options.identifier.id.length > 0);
111
- assert(`buildBaseURL: You must pass \`identifiers\` as part of options`, options.op !== 'findMany' || options.identifiers.every(i => typeof i.id === 'string' && i.id.length > 0));
112
- assert(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'type'`, options.op === 'findMany' || typeof options.identifier.type === 'string' && options.identifier.type.length > 0);
113
- assert(`buildBaseURL: You must pass valid \`identifiers\` as part of options, expected 'type'`, options.op !== 'findMany' || typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0);
159
+ assert(`buildBaseURL: You must pass \`op\` as part of options`, hasResourcePath(options) || typeof options.op === 'string' && options.op.length > 0);
160
+ assert(`buildBaseURL: You must pass \`identifier\` as part of options`, hasResourcePath(options) || options.op === 'findMany' || options.identifier && typeof options.identifier === 'object');
161
+ assert(`buildBaseURL: You must pass \`identifiers\` as part of options`, hasResourcePath(options) || options.op !== 'findMany' || options.identifiers && Array.isArray(options.identifiers) && options.identifiers.length > 0 && options.identifiers.every(i => i && typeof i === 'object'));
162
+ assert(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'id'`, hasResourcePath(options) || !isOperationWithPrimaryRecord(options) || typeof options.identifier.id === 'string' && options.identifier.id.length > 0);
163
+ assert(`buildBaseURL: You must pass \`identifiers\` as part of options`, hasResourcePath(options) || options.op !== 'findMany' || options.identifiers.every(i => typeof i.id === 'string' && i.id.length > 0));
164
+ assert(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'type'`, hasResourcePath(options) || options.op === 'findMany' || typeof options.identifier.type === 'string' && options.identifier.type.length > 0);
165
+ assert(`buildBaseURL: You must pass valid \`identifiers\` as part of options, expected 'type'`, hasResourcePath(options) || options.op !== 'findMany' || typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0);
114
166
 
115
167
  // prettier-ignore
116
168
  const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : '';
@@ -120,7 +172,7 @@ function buildBaseURL(urlOptions) {
120
172
  namespace
121
173
  } = options;
122
174
  const fieldPath = 'fieldPath' in options ? options.fieldPath : '';
123
- assert(`buildBaseURL: You tried to build a ${String(options.op)} request to ${resourcePath} but op must be one of "${['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord', 'createRecord', 'query', 'findMany'].join('","')}".`, ['findRecord', 'query', 'findMany', 'findRelatedCollection', 'findRelatedRecord', 'createRecord', 'updateRecord', 'deleteRecord'].includes(options.op));
175
+ assert(`buildBaseURL: You tried to build a url for a ${String('op' in options ? options.op + ' ' : '')}request to ${resourcePath} but resourcePath must be set or op must be one of "${['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord', 'createRecord', 'query', 'findMany'].join('","')}".`, hasResourcePath(options) || ['findRecord', 'query', 'findMany', 'findRelatedCollection', 'findRelatedRecord', 'createRecord', 'updateRecord', 'deleteRecord'].includes(options.op));
124
176
  assert(`buildBaseURL: host must NOT end with '/', received '${host}'`, host === '/' || !host.endsWith('/'));
125
177
  assert(`buildBaseURL: namespace must NOT start with '/', received '${namespace}'`, !namespace.startsWith('/'));
126
178
  assert(`buildBaseURL: namespace must NOT end with '/', received '${namespace}'`, !namespace.endsWith('/'));
@@ -130,8 +182,9 @@ function buildBaseURL(urlOptions) {
130
182
  assert(`buildBaseURL: fieldPath must NOT end with '/', received '${fieldPath}'`, !fieldPath.endsWith('/'));
131
183
  assert(`buildBaseURL: idPath must NOT start with '/', received '${idPath}'`, !idPath.startsWith('/'));
132
184
  assert(`buildBaseURL: idPath must NOT end with '/', received '${idPath}'`, !idPath.endsWith('/'));
133
- const url = [host === '/' ? '' : host, namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
134
- return host ? url : `/${url}`;
185
+ const hasHost = host !== '' && host !== '/';
186
+ const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
187
+ return hasHost ? url : `/${url}`;
135
188
  }
136
189
  const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = {
137
190
  arrayFormat: 'comma'
@@ -140,20 +193,56 @@ function handleInclude(include) {
140
193
  assert(`Expected include to be a string or array, got ${typeof include}`, typeof include === 'string' || Array.isArray(include));
141
194
  return typeof include === 'string' ? include.split(',') : include;
142
195
  }
143
- function filterEmpty(obj) {
196
+
197
+ /**
198
+ * filter out keys of an object that have falsy values or point to empty arrays
199
+ * returning a new object with only those keys that have truthy values / non-empty arrays
200
+ *
201
+ * @method filterEmpty
202
+ * @static
203
+ * @public
204
+ * @for @ember-data/request-utils
205
+ * @param {Record<string, Serializable>} source object to filter keys with empty values from
206
+ * @return {Record<string, Serializable>} A new object with the keys that contained empty values removed
207
+ */
208
+ function filterEmpty(source) {
144
209
  const result = {};
145
- for (const key in obj) {
146
- const value = obj[key];
147
- if (value) {
210
+ for (const key in source) {
211
+ const value = source[key];
212
+ // Allow `0` and `false` but filter falsy values that indicate "empty"
213
+ if (value !== undefined && value !== null && value !== '') {
148
214
  if (!Array.isArray(value) || value.length > 0) {
149
- result[key] = obj[key];
215
+ result[key] = source[key];
150
216
  }
151
217
  }
152
218
  }
153
219
  return result;
154
220
  }
221
+
222
+ /**
223
+ * Sorts query params by both key and value returning a new URLSearchParams
224
+ * object with the keys inserted in sorted order.
225
+ *
226
+ * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
227
+ *
228
+ * Options:
229
+ * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
230
+ *
231
+ * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
232
+ * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
233
+ * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
234
+ * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
235
+ *
236
+ * @method sortQueryParams
237
+ * @static
238
+ * @public
239
+ * @for @ember-data/request-utils
240
+ * @param {URLSearchParams | object} params
241
+ * @param {object} options
242
+ * @return {URLSearchParams} A URLSearchParams with keys inserted in sorted order
243
+ */
155
244
  function sortQueryParams(params, options) {
156
- options = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
245
+ const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
157
246
  const paramsIsObject = !(params instanceof URLSearchParams);
158
247
  const urlParams = new URLSearchParams();
159
248
  const dictionaryParams = paramsIsObject ? params : {};
@@ -180,7 +269,7 @@ function sortQueryParams(params, options) {
180
269
  const value = dictionaryParams[key];
181
270
  if (Array.isArray(value)) {
182
271
  value.sort();
183
- switch (options.arrayFormat) {
272
+ switch (opts.arrayFormat) {
184
273
  case 'indices':
185
274
  value.forEach((v, i) => {
186
275
  urlParams.append(`${key}[${i}]`, String(v));
@@ -207,22 +296,79 @@ function sortQueryParams(params, options) {
207
296
  });
208
297
  return urlParams;
209
298
  }
299
+
300
+ /**
301
+ * Sorts query params by both key and value, returning a query params string
302
+ *
303
+ * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
304
+ *
305
+ * Options:
306
+ * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
307
+ *
308
+ * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
309
+ * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
310
+ * 'repeat': appends the key for every value e.g. `ids=1&ids=2`
311
+ * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
312
+ *
313
+ * @method buildQueryParams
314
+ * @static
315
+ * @public
316
+ * @for @ember-data/request-utils
317
+ * @param {URLSearchParams | object} params
318
+ * @param {object} [options]
319
+ * @return {string} A sorted query params string without the leading `?`
320
+ */
210
321
  function buildQueryParams(params, options) {
211
322
  return sortQueryParams(params, options).toString();
212
323
  }
213
324
  const NUMERIC_KEYS = new Set(['max-age', 's-maxage', 'stale-if-error', 'stale-while-revalidate']);
325
+
326
+ /**
327
+ * Parses a string Cache-Control header value into an object with the following structure:
328
+ *
329
+ * ```ts
330
+ * interface CacheControlValue {
331
+ * immutable?: boolean;
332
+ * 'max-age'?: number;
333
+ * 'must-revalidate'?: boolean;
334
+ * 'must-understand'?: boolean;
335
+ * 'no-cache'?: boolean;
336
+ * 'no-store'?: boolean;
337
+ * 'no-transform'?: boolean;
338
+ * 'only-if-cached'?: boolean;
339
+ * private?: boolean;
340
+ * 'proxy-revalidate'?: boolean;
341
+ * public?: boolean;
342
+ * 's-maxage'?: number;
343
+ * 'stale-if-error'?: number;
344
+ * 'stale-while-revalidate'?: number;
345
+ * }
346
+ * ```
347
+ * @method parseCacheControl
348
+ * @static
349
+ * @public
350
+ * @for @ember-data/request-utils
351
+ * @param {string} header
352
+ * @return {CacheControlValue}
353
+ */
214
354
  function parseCacheControl(header) {
215
355
  let key = '';
216
356
  let value = '';
217
357
  let isParsingKey = true;
218
- let cacheControlValue = {};
358
+ const cacheControlValue = {};
359
+ function parseCacheControlValue(stringToParse) {
360
+ const parsedValue = Number.parseInt(stringToParse);
361
+ assert(`Invalid Cache-Control value, expected a number but got - ${stringToParse}`, !Number.isNaN(parsedValue));
362
+ return parsedValue;
363
+ }
219
364
  for (let i = 0; i < header.length; i++) {
220
- let char = header.charAt(i);
365
+ const char = header.charAt(i);
221
366
  if (char === ',') {
222
367
  assert(`Invalid Cache-Control value, expected a value`, !isParsingKey || !NUMERIC_KEYS.has(key));
223
368
  assert(`Invalid Cache-Control value, expected a value after "=" but got ","`, i === 0 || header.charAt(i - 1) !== '=');
224
369
  isParsingKey = true;
225
- cacheControlValue[key] = NUMERIC_KEYS.has(key) ? Number.parseInt(value) : true;
370
+ // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
371
+ cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
226
372
  key = '';
227
373
  value = '';
228
374
  continue;
@@ -237,7 +383,8 @@ function parseCacheControl(header) {
237
383
  value += char;
238
384
  }
239
385
  if (i === header.length - 1) {
240
- cacheControlValue[key] = NUMERIC_KEYS.has(key) ? Number.parseInt(value) : true;
386
+ // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
387
+ cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
241
388
  }
242
389
  }
243
390
  return cacheControlValue;
@@ -257,17 +404,231 @@ function isStale(headers, expirationTime) {
257
404
  const result = now > deadline;
258
405
  return result;
259
406
  }
407
+ /**
408
+ * A basic LifetimesService that can be added to the Store service.
409
+ *
410
+ * Determines staleness based on time since the request was last received from the API
411
+ * using the `date` header.
412
+ *
413
+ * Invalidates any request for which `cacheOptions.types` was provided when a createRecord
414
+ * request for that type is successful.
415
+ *
416
+ * For this to work, the `createRecord` request must include the `cacheOptions.types` array
417
+ * with the types that should be invalidated, or its request should specify the identifiers
418
+ * of the records that are being created via `records`. Providing both is valid.
419
+ *
420
+ * > [!NOTE]
421
+ * > only requests that had specified `cacheOptions.types` and occurred prior to the
422
+ * > createRecord request will be invalidated. This means that a given request should always
423
+ * > specify the types that would invalidate it to opt into this behavior. Abstracting this
424
+ * > behavior via builders is recommended to ensure consistency.
425
+ *
426
+ * This allows the Store's CacheHandler to determine if a request is expired and
427
+ * should be refetched upon next request.
428
+ *
429
+ * The `Fetch` handler provided by `@ember-data/request/fetch` will automatically
430
+ * add the `date` header to responses if it is not present.
431
+ *
432
+ * > [!NOTE]
433
+ * > Date headers do not have millisecond precision, so expiration times should
434
+ * > generally be larger than 1000ms.
435
+ *
436
+ * Usage:
437
+ *
438
+ * ```ts
439
+ * import { LifetimesService } from '@ember-data/request-utils';
440
+ * import DataStore from '@ember-data/store';
441
+ *
442
+ * // ...
443
+ *
444
+ * export class Store extends DataStore {
445
+ * constructor(args) {
446
+ * super(args);
447
+ * this.lifetimes = new LifetimesService({ apiCacheSoftExpires: 30_000, apiCacheHardExpires: 60_000 });
448
+ * }
449
+ * }
450
+ * ```
451
+ *
452
+ * @class LifetimesService
453
+ * @public
454
+ * @module @ember-data/request-utils
455
+ */
260
456
  class LifetimesService {
261
- constructor(store, config) {
262
- this.store = store;
263
- this.config = config;
457
+ _getStore(store) {
458
+ let set = this._stores.get(store);
459
+ if (!set) {
460
+ set = {
461
+ invalidated: new Set(),
462
+ types: new Map()
463
+ };
464
+ this._stores.set(store, set);
465
+ }
466
+ return set;
467
+ }
468
+ constructor(config) {
469
+ this._stores = new WeakMap();
470
+ const _config = arguments.length === 1 ? config : arguments[1];
471
+ deprecate(`Passing a Store to the LifetimesService is deprecated, please pass only a config instead.`, arguments.length === 1, {
472
+ id: 'ember-data:request-utils:lifetimes-service-store-arg',
473
+ since: {
474
+ enabled: '5.4',
475
+ available: '5.4'
476
+ },
477
+ for: '@ember-data/request-utils',
478
+ until: '6.0'
479
+ });
480
+ assert(`You must pass a config to the LifetimesService`, _config);
481
+ assert(`You must pass a apiCacheSoftExpires to the LifetimesService`, typeof _config.apiCacheSoftExpires === 'number');
482
+ assert(`You must pass a apiCacheHardExpires to the LifetimesService`, typeof _config.apiCacheHardExpires === 'number');
483
+ this.config = _config;
484
+ }
485
+
486
+ /**
487
+ * Invalidate a request by its identifier for a given store instance.
488
+ *
489
+ * While the store argument may seem redundant, the lifetimes service
490
+ * is designed to be shared across multiple stores / forks
491
+ * of the store.
492
+ *
493
+ * ```ts
494
+ * store.lifetimes.invalidateRequest(store, identifier);
495
+ * ```
496
+ *
497
+ * @method invalidateRequest
498
+ * @public
499
+ * @param {StableDocumentIdentifier} identifier
500
+ * @param {Store} store
501
+ */
502
+ invalidateRequest(identifier, store) {
503
+ this._getStore(store).invalidated.add(identifier.lid);
504
+ }
505
+
506
+ /**
507
+ * Invalidate all requests associated to a specific type
508
+ * for a given store instance.
509
+ *
510
+ * While the store argument may seem redundant, the lifetimes service
511
+ * is designed to be shared across multiple stores / forks
512
+ * of the store.
513
+ *
514
+ * This invalidation is done automatically when using this service
515
+ * for both the CacheHandler and the LegacyNetworkHandler.
516
+ *
517
+ * ```ts
518
+ * store.lifetimes.invalidateRequestsForType(store, 'person');
519
+ * ```
520
+ *
521
+ * @method invalidateRequestsForType
522
+ * @public
523
+ * @param {string} type
524
+ * @param {Store} store
525
+ */
526
+ invalidateRequestsForType(type, store) {
527
+ const storeCache = this._getStore(store);
528
+ const set = storeCache.types.get(type);
529
+ if (set) {
530
+ set.forEach(id => {
531
+ storeCache.invalidated.add(id);
532
+ });
533
+ }
534
+ }
535
+
536
+ /**
537
+ * Invoked when a request has been fulfilled from the configured request handlers.
538
+ * This is invoked by the CacheHandler for both foreground and background requests
539
+ * once the cache has been updated.
540
+ *
541
+ * Note, this is invoked by the CacheHandler regardless of whether
542
+ * the request has a cache-key.
543
+ *
544
+ * This method should not be invoked directly by consumers.
545
+ *
546
+ * @method didRequest
547
+ * @public
548
+ * @param {ImmutableRequestInfo} request
549
+ * @param {ImmutableResponse} response
550
+ * @param {Store} store
551
+ * @param {StableDocumentIdentifier | null} identifier
552
+ * @return {void}
553
+ */
554
+ didRequest(request, response, identifier, store) {
555
+ // if this is a successful createRecord request, invalidate the cacheKey for the type
556
+ if (request.op === 'createRecord') {
557
+ const statusNumber = response?.status ?? 0;
558
+ if (statusNumber >= 200 && statusNumber < 400) {
559
+ const types = new Set(request.records?.map(r => r.type));
560
+ const additionalTypes = request.cacheOptions?.types;
561
+ additionalTypes?.forEach(type => {
562
+ types.add(type);
563
+ });
564
+ types.forEach(type => {
565
+ this.invalidateRequestsForType(type, store);
566
+ });
567
+ }
568
+
569
+ // add this document's cacheKey to a map for all associated types
570
+ // it is recommended to only use this for queries
571
+ } else if (identifier && request.cacheOptions?.types?.length) {
572
+ const storeCache = this._getStore(store);
573
+ request.cacheOptions?.types.forEach(type => {
574
+ const set = storeCache.types.get(type);
575
+ if (set) {
576
+ set.add(identifier.lid);
577
+ storeCache.invalidated.delete(identifier.lid);
578
+ } else {
579
+ storeCache.types.set(type, new Set([identifier.lid]));
580
+ }
581
+ });
582
+ }
264
583
  }
265
- isHardExpired(identifier) {
266
- const cached = this.store.cache.peekRequest(identifier);
584
+
585
+ /**
586
+ * Invoked to determine if the request may be fulfilled from cache
587
+ * if possible.
588
+ *
589
+ * Note, this is only invoked by the CacheHandler if the request has
590
+ * a cache-key.
591
+ *
592
+ * If no cache entry is found or the entry is hard expired,
593
+ * the request will be fulfilled from the configured request handlers
594
+ * and the cache will be updated before returning the response.
595
+ *
596
+ * @method isHardExpired
597
+ * @public
598
+ * @param {StableDocumentIdentifier} identifier
599
+ * @param {Store} store
600
+ * @return {boolean} true if the request is considered hard expired
601
+ */
602
+ isHardExpired(identifier, store) {
603
+ // if we are explicitly invalidated, we are hard expired
604
+ const storeCache = this._getStore(store);
605
+ if (storeCache.invalidated.has(identifier.lid)) {
606
+ return true;
607
+ }
608
+ const cache = store.cache;
609
+ const cached = cache.peekRequest(identifier);
267
610
  return !cached || !cached.response || isStale(cached.response.headers, this.config.apiCacheHardExpires);
268
611
  }
269
- isSoftExpired(identifier) {
270
- const cached = this.store.cache.peekRequest(identifier);
612
+
613
+ /**
614
+ * Invoked if `isHardExpired` is false to determine if the request
615
+ * should be update behind the scenes if cache data is already available.
616
+ *
617
+ * Note, this is only invoked by the CacheHandler if the request has
618
+ * a cache-key.
619
+ *
620
+ * If true, the request will be fulfilled from cache while a backgrounded
621
+ * request is made to update the cache via the configured request handlers.
622
+ *
623
+ * @method isSoftExpired
624
+ * @public
625
+ * @param {StableDocumentIdentifier} identifier
626
+ * @param {Store} store
627
+ * @return {boolean} true if the request is considered soft expired
628
+ */
629
+ isSoftExpired(identifier, store) {
630
+ const cache = store.cache;
631
+ const cached = cache.peekRequest(identifier);
271
632
  return !cached || !cached.response || isStale(cached.response.headers, this.config.apiCacheSoftExpires);
272
633
  }
273
634
  }