https://github.com/natemoo-re/ultrafetch
RFC-7234 compliant caching for any `fetch` implementation
https://github.com/natemoo-re/ultrafetch
cache cache-control etag fetch http-cache node node-fetch rfc7234
Last synced: about 1 year ago
JSON representation
RFC-7234 compliant caching for any `fetch` implementation
- Host: GitHub
- URL: https://github.com/natemoo-re/ultrafetch
- Owner: natemoo-re
- Created: 2021-12-12T14:31:35.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-11-16T23:36:52.000Z (over 3 years ago)
- Last Synced: 2025-03-30T03:09:09.122Z (about 1 year ago)
- Topics: cache, cache-control, etag, fetch, http-cache, node, node-fetch, rfc7234
- Language: TypeScript
- Homepage:
- Size: 161 KB
- Stars: 223
- Watchers: 2
- Forks: 6
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
# `ultrafetch`
Modular utilities for enhancing `fetch` behavior. Bring Your Own Fetch implementation supports both [`node-fetch`](https://github.com/node-fetch/node-fetch) and [`unidici`](https://github.com/nodejs/undici)'s `fetch` (globally available in `node@18+`).
## `withCache`
The `withCache` function enhances `fetch` with [RFC-7234](https://httpwg.org/specs/rfc7234.html) compliant cache behavior. The default cache is a simple in-memory `Map`, but custom `cache`s are also supported.
```js
import { withCache } from "ultrafetch";
const enhancedFetch = withCache(fetch);
```
Any custom `cache` that adheres to a `Map` interface is valid.
```ts
import { withCache } from "ultrafetch";
class MyCache implements Map {
clear(): void;
delete(key: K): boolean;
get(key: K): V| undefined>;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
const enhancedFetch = withCache(fetch, { cache: new MyCache() });
```
Custom `cache`s can also use the `AsyncMap` interface, which is the same as a standard `Map` but each method is `async`.
```ts
import type { AsyncMap } from "ultrafetch";
import { withCache } from "ultrafetch";
class MyAsyncCache implements AsyncMap {
clear(): Promise;
delete(key: K): Promise;
get(key: K): Promise;
has(key: K): Promise;
set(key: K, value: V): Promise;
readonly size: number;
}
const enhancedFetch = withCache(fetch, { cache: new MyAsyncCache() });
```
### `isCached`
The `isCached` export can be used to determine if a given `Response` was returned from the cache or not.
```ts
import { withCache, isCached } from "ultrafetch";
const enhancedFetch = withCache(fetch);
const responseA = await enhancedFetch('https://example.com');
isCached(responseA) // false
const responseB = await enhancedFetch('https://example.com');
isCached(responseB) // true
```