@studiocms/cfetch 0.1.1 → 0.1.3

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
@@ -60,7 +60,7 @@ export default defineConfig({
60
60
 
61
61
  ### Usage
62
62
 
63
- You can import the cachedFetch function anywhere you would use a normal `fetch` call. `cfetch` adapts the same default options as fetch,
63
+ You can import the `cFetch` function anywhere and use it as you would use a normal `fetch` call. `cFetch` adapts the same default options as `fetch`:
64
64
 
65
65
  ```astro
66
66
  ---
@@ -69,30 +69,32 @@ import { cFetch } from 'c:fetch';
69
69
  const response = await cFetch(
70
70
  'https://example.com', // string | URL | Request
71
71
  { /* Normal fetch init optional options here, method, mode, etc. */ },
72
- { lifetime: "1h" } // Optional, allows changing the default lifetime of the cache
73
- );
72
+ { lifetime: "1h" }, // Optional, allows changing the default lifetime of the cache
73
+ 'json', // Optional, allows changing the type of response object to be cached. 'json' (default) or 'text'
74
+ );
74
75
 
75
76
  const html = await response.text();
76
77
  ---
77
78
  ```
78
79
 
79
- If you are also wanting the other available metadata (such as `lastChecked` value which is the last time the cache was updated) then you can add the following prop to cached fetch, changing the shape of the data output to the following:
80
+ If you need to access the other available metadata (such as the `lastChecked` value which provides the last time the cache was updated), you can pass `true` as the fourth parameter, which will change the returned object to the following:
80
81
 
81
82
  ```astro
82
83
  ---
83
84
  import { cFetch } from 'c:fetch';
84
85
 
85
- const { lastCheck, data: response } = await cFetch(
86
- 'https://example.com', // string | URL | Request
87
- { /* Normal fetch init optional options here, method, mode, etc. */ },
88
- { lifetime: "1h" }, // Optional, allows changing the default lifetime of the cache
89
- true
90
- );
86
+ const { lastCheck, data } = await cFetch(
87
+ 'https://example.com',
88
+ { /* ... */ },
89
+ { lifetime: "1h" },
90
+ 'json',
91
+ true // Changes the the output to include the lastCheck value
92
+ );
91
93
 
92
- const html = await response.text();
94
+ const html = await data.text();
93
95
  ---
94
96
  ```
95
97
 
96
98
  ## Licensing
97
99
 
98
- [MIT Licensed](https://github.com/withstudiocms/cfetch/blob/main/LICENSE).
100
+ [MIT Licensed](https://github.com/withstudiocms/cfetch/blob/main/LICENSE).
package/dist/cache.d.ts CHANGED
@@ -62,6 +62,8 @@ declare module 'c:fetch' {
62
62
  * @param input - The input to the fetch function, typically a URL or Request object.
63
63
  * @param init - An optional configuration object for the fetch request.
64
64
  * @param cacheConfig - Partial configuration for the cache behavior. Defaults to `defaultConfig`.
65
+ * @param type - Optional parameter specifying the expected response body format.
66
+ * Can be either 'json' or 'text'. Determines how the response body is processed.
65
67
  * @param metadata - A boolean indicating whether to return the full cached object (including metadata)
66
68
  * or just the data. Defaults to `false`.
67
69
  * @returns The fetched or cached data. If `full` is `true`, returns an object containing
@@ -71,12 +73,14 @@ declare module 'c:fetch' {
71
73
  export function cFetch(
72
74
  input: Input,
73
75
  init?: Init,
74
- cacheConfig?: Partial<CacheConfig>
76
+ cacheConfig?: Partial<CacheConfig>,
77
+ type?: 'json' | 'text'
75
78
  ): Promise<Response>;
76
79
  export function cFetch(
77
80
  input: Input,
78
81
  init?: Init,
79
82
  cacheConfig?: Partial<CacheConfig>,
83
+ type?: 'json' | 'text',
80
84
  metadata?: boolean
81
85
  ): Promise<CacheDataValue>;
82
86
  }
@@ -3,6 +3,9 @@ export type { CacheConfig };
3
3
  /**
4
4
  * Exported for tests
5
5
  */
6
- export declare const cachedData: Map<string, CacheDataValue>;
7
- export declare function cFetch(input: Input, init?: Init, cacheConfig?: Partial<CacheConfig>): Promise<Response>;
8
- export declare function cFetch(input: Input, init?: Init, cacheConfig?: Partial<CacheConfig>, metadata?: boolean): Promise<CacheDataValue>;
6
+ export declare const cachedData: Map<string, {
7
+ lastCheck: Date;
8
+ data: any;
9
+ }>;
10
+ export declare function cFetch(input: Input, init?: Init, cacheConfig?: Partial<CacheConfig>, type?: 'json' | 'text'): Promise<Response>;
11
+ export declare function cFetch(input: Input, init?: Init, cacheConfig?: Partial<CacheConfig>, type?: 'json' | 'text', metadata?: boolean): Promise<CacheDataValue>;
package/dist/wrappers.js CHANGED
@@ -6,32 +6,40 @@ const defaultConfig = await import("virtual:cfetch/config").then((mod) => {
6
6
  return _config;
7
7
  });
8
8
  const cachedData = /* @__PURE__ */ new Map();
9
- async function cFetch(input, init = void 0, cacheConfig = defaultConfig, metadata = false) {
9
+ async function cFetch(input, init = {}, cacheConfig = defaultConfig, type = "json", metadata = false) {
10
10
  if (init?.method && init.method !== "GET") {
11
11
  console.warn(
12
12
  "Warning: cFetch is designed for GET requests. Using it with other methods will not cache the response."
13
13
  );
14
- const newResponse = fetch(input, init);
15
- return metadata ? { lastCheck: /* @__PURE__ */ new Date(), data: newResponse } : newResponse;
14
+ const response = await fetch(input, init);
15
+ const data = type === "json" ? await response.clone().json() : await response.clone().text();
16
+ const result = new Response(type === "json" ? JSON.stringify(data) : data, response);
17
+ return metadata ? { lastCheck: /* @__PURE__ */ new Date(), data: result } : result;
16
18
  }
17
- const { lifetime } = {
18
- ...defaultConfig,
19
- ...cacheConfig
20
- };
21
- const storedData = cachedData.get(input.toString());
19
+ const { lifetime } = { ...defaultConfig, ...cacheConfig };
20
+ const key = input.toString();
21
+ const storedData = cachedData.get(key);
22
22
  if (!storedData || isOlderThan(storedData.lastCheck, lifetime)) {
23
- const newResponse = await fetch(input, init);
24
- if (!newResponse.ok) {
23
+ const response = await fetch(input, init);
24
+ if (!response.ok) {
25
25
  if (!storedData) {
26
26
  throw new Error("Failed to retrieve cached data, and failed to fetch new data");
27
27
  }
28
- return metadata ? storedData : storedData.data;
28
+ const fallback = new Response(
29
+ type === "json" ? JSON.stringify(storedData.data) : storedData.data
30
+ );
31
+ return metadata ? { ...storedData, data: fallback } : fallback;
29
32
  }
30
- const newCachedData = { lastCheck: /* @__PURE__ */ new Date(), data: newResponse };
31
- cachedData.set(input.toString(), newCachedData);
32
- return metadata ? newCachedData : newResponse;
33
+ const data = type === "json" ? await response.clone().json() : await response.clone().text();
34
+ const newCachedData = { lastCheck: /* @__PURE__ */ new Date(), data };
35
+ cachedData.set(key, newCachedData);
36
+ const result = new Response(type === "json" ? JSON.stringify(data) : data, response);
37
+ return metadata ? { ...newCachedData, data: result } : result;
33
38
  }
34
- return metadata ? storedData : storedData.data;
39
+ const cachedResponse = new Response(
40
+ type === "json" ? JSON.stringify(storedData.data) : storedData.data
41
+ );
42
+ return metadata ? { ...storedData, data: cachedResponse } : cachedResponse;
35
43
  }
36
44
  export {
37
45
  cFetch,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@studiocms/cfetch",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Astro integration that allows you to have a cached fetch function in your Astro SSR project.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://studiocms.dev",