bv-ui-core 2.9.7 → 2.9.9

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.
@@ -9,6 +9,8 @@ The BvFetch module provides methods to cache duplicate API calls and interact wi
9
9
  `shouldCache (Function):` A function that takes the API response JSON as input and returns a boolean indicating whether to cache the response or not. This allows you to implement custom logic based on the response content. If caching is desired, the function should return true; otherwise, false.
10
10
  `cacheName (String):` Optional. Specifies the name of the cache to be used. If not provided, the default cache name 'bvCache' will be used.
11
11
  `cacheLimit (Integer)`: Optional. Specifies the cache size limit for the cache storage. Its value should be in MB. Default value is 10 MB.
12
+ `excludeHeaders (Array[String])`: Includes the list of headers that are excluded from the cacheKey
13
+
12
14
 
13
15
  ## bvFetchFunc Method Parameters
14
16
  `url (String):` The URL of the API endpoint to fetch data from.
@@ -17,11 +19,16 @@ The BvFetch module provides methods to cache duplicate API calls and interact wi
17
19
  ## bvFetchFunc Return Value
18
20
  `Promise<Response>:` A promise that resolves to the API response. If the response is cached, it returns the cached response. Otherwise, it fetches data from the API endpoint, caches the response according to the caching logic, and returns the fetched response.
19
21
 
20
- ## generateCacheKey Method Parameters:
21
- `url (String):` The URL of the API endpoint.
22
- `options (Object):` Optional request options.
23
- ## generateCacheKey Return Value:
24
- `Request:` The generated cache key.
22
+ ## generateCacheKey Method
23
+
24
+ Generates a cache key as a Request object for a given URL and options, filtering out any headers specified in `excludeHeaders`.
25
+
26
+ **Parameters:**
27
+ - `url (String)`: The URL of the API endpoint.
28
+ - `options (Object)`: *(Optional)* Request options (e.g., headers, method, etc.).
29
+
30
+ **Returns:**
31
+ `Request`: The generated Request object to be used as a cache key.
25
32
 
26
33
  ## retrievecachedRequests Method
27
34
  Retrieves cached Requests from the cache storage associated with the provided cache name.
@@ -77,8 +84,10 @@ var BvFetch = require('bv-ui-core/lib/bvFetch')
77
84
 
78
85
  // Initialize BV Fetch instance
79
86
  const bvFetch = new BVFetch({
80
- canBeCached: canBeCached, // optional
81
- cacheName: "bvCache" // optional, default is "bvCache"
87
+ shouldCache: function(responseJson) => { /* return true or false */ }, // optional, callback function to check if the response is cachable
88
+ cacheName: "bvCache" // optional, default is "bvCache"
89
+ cacheLimit: 10, // optional but default is 10
90
+ excludeHeaders: [], // optional, list of headers to be excluded from cache
82
91
  });
83
92
 
84
93
  // Make API calls using bvFetchFunc method
@@ -5,12 +5,13 @@
5
5
 
6
6
  const { fetch } = require('../polyfills/fetch')
7
7
 
8
- module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
8
+ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit, excludeHeaders = [] }) {
9
9
  this.shouldCache = shouldCache;
10
10
  this.cacheName = cacheName || 'bvCache';
11
11
  this.cacheLimit = cacheLimit * 1024 * 1024 || 10 * 1024 * 1024;
12
12
  this.fetchPromises = new Map();
13
13
  this.cachedRequests = new Set();
14
+ this.excludeHeaders = excludeHeaders;
14
15
 
15
16
  /**
16
17
  * Checks if a request is present in a set of cached URLs.
@@ -37,7 +38,7 @@ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
37
38
  if (cachedHeaders.length !== keyHeaders.length) {
38
39
  return false; // Different number of headers
39
40
  }
40
-
41
+ // Check if all headers match
41
42
  return cachedHeaders.every(([key, value]) => {
42
43
  return cacheKey.headers.get(key) === value;
43
44
  });
@@ -58,11 +59,43 @@ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
58
59
  * @returns {Request} The created Request object.
59
60
  */
60
61
 
62
+ /**
63
+ * Generates a cache key as a Request object for the given URL and options.
64
+ * Filters out headers specified in `excludeHeaders` from the options before creating the Request.
65
+ *
66
+ * @param {string} url - The URL of the API endpoint.
67
+ * @param {Object} options - Optional request options (e.g., headers, method, etc.).
68
+ * @returns {Request} The generated Request object to be used as a cache key.
69
+ */
61
70
  this.generateCacheKey = (url, options) => {
62
- const key = new Request(url, options);
71
+ const filteredOptions = Object.assign({}, options);
72
+ if (filteredOptions.headers) {
73
+ const newHeaders = new Headers();
74
+ for (const [key, value] of Object.entries(filteredOptions.headers)) {
75
+ if (!this.excludeHeaders.includes(key)) {
76
+ newHeaders.set(key, value);
77
+ }
78
+ }
79
+ filteredOptions.headers = newHeaders;
80
+ }
81
+ const key = new Request(url, filteredOptions);
63
82
  return key;
64
83
  };
65
84
 
85
+ /**
86
+ * Serializes a request object into a JSON string for use as a cache key.
87
+ * The serialization includes the URL, method, and sorted headers of the request.
88
+ * @param {Request} request - The request object to serialize.
89
+ * @returns {string} A JSON string representing the serialized request.
90
+ */
91
+ this.serializeRequestKey = (request) => {
92
+ const url = request.url;
93
+ const method = request.method || 'GET';
94
+ // Convert headers to a sorted array of [key, value] pairs for consistency
95
+ const headersArr = Array.from(request.headers.entries()).sort(([a], [b]) => a.localeCompare(b));
96
+ return JSON.stringify([url, method, { headers: headersArr }]);
97
+ }
98
+
66
99
  /**
67
100
  * Retrieves cached Requests from the cache storage associated with the provided cache name.
68
101
  * @returns {void}
@@ -76,7 +109,9 @@ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
76
109
  keys.forEach(request => {
77
110
  const headers = {};
78
111
  request.headers.forEach((value, key) => {
79
- headers[key] = value;
112
+ if (!this.excludeHeaders.includes(key)) {
113
+ headers[key] = value;
114
+ }
80
115
  });
81
116
 
82
117
  // Generate the cache key with headers and URL
@@ -119,6 +154,15 @@ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
119
154
  this.cacheData = (response, cacheKey) => {
120
155
  const errJson = response.clone();
121
156
  let canBeCached = true;
157
+ if (!response.ok) {
158
+ // If the response is not ok, we don't cache it
159
+ canBeCached = false;
160
+ return;
161
+ }
162
+ if (!response.headers.has('Cache-Control')) {
163
+ canBeCached = false;
164
+ return;
165
+ }
122
166
  // Check for error in response obj
123
167
  errJson.json().then(json => {
124
168
  if (typeof this.shouldCache === 'function') {
@@ -206,11 +250,11 @@ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
206
250
 
207
251
  const cacheKey = this.generateCacheKey(url, options);
208
252
  // If an ongoing fetch promise exists for the URL, return it
209
- if (this.fetchPromises.has(cacheKey)) {
210
- return this.fetchPromises.get(cacheKey).then(res => res.clone());
253
+ if (this.fetchPromises.has(this.serializeRequestKey(cacheKey))) {
254
+ return this.fetchPromises.get(this.serializeRequestKey(cacheKey)).then(res => res.clone());
211
255
  }
212
256
 
213
- // Check if response is available in cache
257
+ // Check if response is available in cache
214
258
  const newPromise = this.fetchFromCache(cacheKey)
215
259
  .then((cachedResponse) => {
216
260
  // If response found in cache, return it
@@ -222,14 +266,14 @@ module.exports = function BvFetch ({ shouldCache, cacheName, cacheLimit }) {
222
266
  });
223
267
 
224
268
  // Store the ongoing fetch promise
225
- this.fetchPromises.set(cacheKey, newPromise);
269
+ this.fetchPromises.set(this.serializeRequestKey(cacheKey), newPromise);
226
270
 
227
271
  //initiate cache cleanUp
228
272
  this.debounceCleanupExpiredCache();
229
273
 
230
274
  // When fetch completes or fails, remove the promise from the store
231
275
  newPromise.finally(() => {
232
- this.fetchPromises.delete(cacheKey);
276
+ this.fetchPromises.delete(this.serializeRequestKey(cacheKey));
233
277
  });
234
278
 
235
279
  return newPromise.then(res => res.clone());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bv-ui-core",
3
- "version": "2.9.7",
3
+ "version": "2.9.9",
4
4
  "license": "Apache 2.0",
5
5
  "description": "Bazaarvoice UI-related JavaScript",
6
6
  "repository": {