@micheldever/fetch
v1.0.4
Published
Data fetching utility class with simple caching support
Downloads
4
Readme
Installation
This package is distributed via npm. You can install it as a dependency in your project by running:
yarn add @micheldever/fetch
Usage
After creating a new instance of the FetchClient
, you can fetch data using the fetch
method:
import { FetchClient } from '@micheldever/fetch';
const client = new FetchClient();
const data = await client.fetch('https://api.example.com/data');
The fetch
method returns a Promise that resolves with the fetched data.
Caching Responses
FetchClient
can cache responses to avoid unnecessary network requests. To enable caching, you
need to provide a StorageEntity
when creating the FetchClient
:
import { FetchClient } from '@micheldever/fetch';
import { MemoryStorageAdapter } from '@micheldever/storage/adapters';
import { StorageEntity } from '@micheldever/storage';
const client = new FetchClient(new StorageEntity(new MemoryStorageAdapter()));
const data = await client.fetch('https://api.example.com/data', { key: ['query'], ttl: 3600000 });
In this example, the response will be cached for 3600000 milliseconds (1 hour). If you fetch the
same URL with the same query key within this time, FetchClient
will return the cached response
instead of making a new network request.
Invalidating the Cache
You can invalidate a cached response using the invalidateCache
method:
await client.invalidateCache(['query']);
Static fetch
For simple data fetching that doesn't require caching you can use the static fetch
method:
const data = FetchClient.fetch('https://api.example.com/data');