@kisaragi-hiu/cached-fetch 0.1.2 → 0.2.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.
Files changed (3) hide show
  1. package/index.d.ts +5 -4
  2. package/index.js +12 -6
  3. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -10,10 +10,11 @@ key: string,
10
10
  /**
11
11
  * A fetcher function, called when the value isn't cached.
12
12
  *
13
- * Should return a Promise<{ text: () => string | Promise<string> }>. This is
14
- * usually a Response, but ProcessOutput from the zx library also fits
15
- * this signature.
13
+ * This can return a string or a Promise<string>.
14
+ *
15
+ * This can also return a Promise<{ text: () => string | Promise<string> }>.
16
+ * This means a Response or zx's ProcessOutput can be used directly.
16
17
  */
17
- fetcher: () => Promise<{
18
+ fetcher: () => string | Promise<string> | Promise<{
18
19
  text: () => string | Promise<string>;
19
20
  }>): Promise<string>;
package/index.js CHANGED
@@ -14,16 +14,22 @@ key,
14
14
  /**
15
15
  * A fetcher function, called when the value isn't cached.
16
16
  *
17
- * Should return a Promise<{ text: () => string | Promise<string> }>. This is
18
- * usually a Response, but ProcessOutput from the zx library also fits
19
- * this signature.
17
+ * This can return a string or a Promise<string>.
18
+ *
19
+ * This can also return a Promise<{ text: () => string | Promise<string> }>.
20
+ * This means a Response or zx's ProcessOutput can be used directly.
20
21
  */
21
22
  fetcher) {
22
23
  const cacheFile = join(tmpdir(), key);
23
24
  const cacheHit = existsSync(cacheFile);
24
- const text = cacheHit
25
- ? readFileSync(cacheFile, { encoding: "utf-8" })
26
- : await (await fetcher()).text();
25
+ let text;
26
+ if (cacheHit) {
27
+ text = readFileSync(cacheFile, { encoding: "utf-8" });
28
+ }
29
+ else {
30
+ const result = await fetcher();
31
+ text = typeof result === "string" ? result : await result.text();
32
+ }
27
33
  if (!cacheHit) {
28
34
  mkdirSync(dirname(cacheFile), { recursive: true });
29
35
  writeFileSync(cacheFile, text, { encoding: "utf-8" });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kisaragi-hiu/cached-fetch",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "A cache in OS tmpdir useful for fetch()",
5
5
  "type": "module",
6
6
  "repository": {