Skip to content

Commit

Permalink
docs: fixed tsdocs and added storages section
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Jan 3, 2022
1 parent 500ac71 commit 4c1e0ec
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 47 deletions.
57 changes: 37 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ const resp2 = await axios.get('https://api.example.com/');
- [Response object](#response-object)
- [response.cached](#responsecached)
- [response.id](#responseid)
- [Storages](#storages)
- [Global Configuration](#global-configuration)
- [config.storage](#configstorage)
- [config.generateKey](#configgeneratekey)
Expand Down Expand Up @@ -437,6 +438,40 @@ the internal code. Remember that, depending on the
[config.keyGenerator](#configgeneratekey), it can be different as the provided on the
[request.id](#requestid).

### Storages

A storage is the main object responsible for saving, retrieving and serializing (if
needed) cache data. There are two simple ones that comes by default:

- [In Memory](src/storage/memory.ts) with `buildMemoryStorage` (Node and Web)
- [Web Cache](src/storage/web-api.ts) with `buildWebStorage` (Web only)

Both of them are included in all bundles.

You can create your own storage by using the `buildStorage` function. Take a look at this
example with [NodeRedis](https://github.com/redis/node-redis) v4.

```js
import { createClient } from 'redis'; // 4.0.1
import { buildStorage } from 'axios-cache-interceptor';

const client = createClient();

await client.connect();

const myCustomStorage = buildStorage({
find: async (key) => {
return await client.get(`axios-cache:${key}`);
},
set: async (key, value) => {
await client.set(`axios-cache:${key}`, JSON.stringify(value));
},
remove: async (key) => {
await client.del(`axios-cache:${key}`);
}
});
```

<br />

## Global Configuration
Expand All @@ -451,27 +486,9 @@ const axios = setupCache(axios, {

### config.storage

The storage used to save the cache. Here will probably be the most changed property.
Defaults to [MemoryStorage](src/storage/memory.ts).

You can create your own implementation by implementing
[CacheStorage](src/storage/types.ts).

There are few built in storage implementations, you can use them by importing:

> With the cdn served bundle, the **MemoryStorage** and **BrowserAxiosStorage** comes by
> default. Just get them by `window.AxiosCacheInterceptor.BrowserAxiosStorage` or
> `window.AxiosCacheInterceptor.MemoryAxiosStorage`.
```js
import {} from 'axios-cache-interceptor/dist/storage/{name}';
```
The storage used to save the cache. Defaults to a simple in-memory storage.

- [MemoryAxiosStorage](src/storage/memory.ts)
`import 'axios-cache-interceptor/dist/storage/memory';`
- [BrowserAxiosStorage](src/storage/browser.ts)
`import 'axios-cache-interceptor/dist/storage/browser';`
- _Maybe your own?_ (PR's are welcome)
See more about storages [here](#storages).

### config.generateKey

Expand Down
4 changes: 2 additions & 2 deletions src/cache/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ export type CacheProperties = {

export interface CacheInstance {
/**
* The storage to save the cache data.
* The storage to save the cache data. Defaults to an in-memory storage.
*
* @default new MemoryAxiosStorage()
* @default buildMemoryStorage()
*/
storage: AxiosStorage;

Expand Down
17 changes: 16 additions & 1 deletion src/storage/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import { Header } from '../util/headers';
import type { AxiosStorage, StaleStorageValue } from './types';

/**
* Builds a custom storage.
*
* @example
*
* ```js
* const myStorage = buildStorage({
* find: () => {...},
* set: () => {...},
* remove: () => {...}
* });
*
* const axios = setupCache(axios, { storage: myStorage });
* ```
*/
export function buildStorage({
set,
find,
Expand All @@ -18,8 +33,8 @@ export function buildStorage({
}

if (
value.state !== 'cached' ||
// Not cached or fresh value
value.state !== 'cached' ||
value.createdAt + value.ttl > Date.now()
) {
return value;
Expand Down
23 changes: 10 additions & 13 deletions src/storage/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,21 @@ export type EmptyStorageValue = {
* **You can create yours with {@link buildStorage} function**
*
* @example
*
* ```js
* const myStorage = buildStorage({
* find: myFindFunction,
* set: mySetFunction,
* remove: myRemoveFunction,
* })
* find: () => {...},
* set: () => {...},
* remove: () => {...}
* });
*
* const axios = setupCache(axios, { storage: myStorage })
* const axios = setupCache(axios, { storage: myStorage });
* ```
*/
export type AxiosStorage = {
/**
* Returns the value for the given key. This method does not have to make checks for cache invalidation or etc. It just return what was previous saved, if present.
* Returns the value for the given key. This method does not have to make checks for
* cache invalidation or etc. It just return what was previous saved, if present.
*/
find: (key: string) => Promise<StorageValue | undefined>;

Expand All @@ -80,14 +82,9 @@ export type AxiosStorage = {
*/
set: (key: string, value: NotEmptyStorageValue) => Promise<void>;

/**
* Removes the value for the given key
*/
/** Removes the value for the given key */
remove: (key: string) => Promise<void>;

/**
* Returns the value for the given key. This method make checks for cache invalidation or etc.
*
*/
/** Returns the value for the given key. This method make checks for cache invalidation or etc. */
get: (key: string) => Promise<StorageValue>;
};
7 changes: 6 additions & 1 deletion src/storage/web-api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { buildStorage } from './build';

/**
* Creates a simple storage. You can persist his data by using `sessionStorage` or
* `localStorage` with it.
*
* **ImplNote**: Without polyfill, this storage only works on browser environments.
*
* @example
*
* ```js
* const fromLocalStorage = buildWebStorage(localStorage);
*
* const fromSessionStorage = buildWebStorage(sessionStorage);
*
* const myStorage = new Storage();
Expand Down
17 changes: 7 additions & 10 deletions test/bundle.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import { isAxiosCacheInterceptor, setupCache } from '../src/cache/create';
import { BrowserAxiosStorage } from '../src/storage/browser';
import { MemoryAxiosStorage } from '../src/storage/memory';
import { AxiosStorage } from '../src/storage/storage';
import { buildMemoryStorage } from '../src/storage/memory';
import { buildWebStorage } from '../src/storage/web-api';

describe('test bundle imports', () => {
it('tests browser ', async () => {
const bundle = await import('../src/index.browser');

expect(bundle.setupCache).toBe(setupCache);
expect(bundle.isAxiosCacheInterceptor).toBe(isAxiosCacheInterceptor);
expect(bundle.AxiosStorage).toBe(AxiosStorage);
expect(bundle.BrowserAxiosStorage).toBe(BrowserAxiosStorage);
expect(bundle.MemoryAxiosStorage).toBe(MemoryAxiosStorage);
expect(bundle.buildMemoryStorage).toBe(buildMemoryStorage);
expect(bundle.buildWebStorage).toBe(buildWebStorage);
});

it('should have basic storages', async () => {
it('test development bundle imports', async () => {
const oldWarn = console.warn;
console.warn = jest.fn();

Expand All @@ -24,9 +22,8 @@ describe('test bundle imports', () => {

expect(bundle.setupCache).toBe(setupCache);
expect(bundle.isAxiosCacheInterceptor).toBe(isAxiosCacheInterceptor);
expect(bundle.AxiosStorage).toBe(AxiosStorage);
expect(bundle.BrowserAxiosStorage).toBe(BrowserAxiosStorage);
expect(bundle.MemoryAxiosStorage).toBe(MemoryAxiosStorage);
expect(bundle.buildMemoryStorage).toBe(buildMemoryStorage);
expect(bundle.buildWebStorage).toBe(buildWebStorage);

console.warn = oldWarn;
});
Expand Down

0 comments on commit 4c1e0ec

Please sign in to comment.