refactor: prevent confusion by renaming createCache to useCache

This commit is contained in:
arthurfiorette 2021-12-30 13:54:23 -03:00
parent 6bf732be9e
commit 4a0a99ff28
No known key found for this signature in database
GPG Key ID: 9D190CD53C53C555
8 changed files with 130 additions and 73 deletions

View File

@ -79,10 +79,10 @@ Axios Cache Interceptor</h1>
```ts ```ts
import axios from 'axios'; import axios from 'axios';
import { createCache, SessionCacheStorage } from 'axios-cache-interceptor'; import { setupCache, SessionCacheStorage } from 'axios-cache-interceptor';
// An axios instance with modified types // An axios instance with modified types
const api = createCache(axios.create(), { const api = setupCache(axios.create(), {
/* options */ /* options */
}); });
@ -107,6 +107,7 @@ const resp2 = await api.get('https://api.example.com/');
- [Support list](#support-list) - [Support list](#support-list)
- [Getting Started](#getting-started) - [Getting Started](#getting-started)
- [Compiled code](#compiled-code) - [Compiled code](#compiled-code)
- [Typescript users](#typescript-users)
- [Basic Knowledge](#basic-knowledge) - [Basic Knowledge](#basic-knowledge)
- [Request id](#request-id) - [Request id](#request-id)
- [Response object](#response-object) - [Response object](#response-object)
@ -158,9 +159,9 @@ yarn add axios axios-cache-interceptor
``` ```
```js ```js
const { createCache } = require('axios-cache-interceptor'); const { setupCache } = require('axios-cache-interceptor');
// or // or
import { createCache } from 'axios-cache-interceptor'; import { setupCache } from 'axios-cache-interceptor';
``` ```
### Via CDN ### Via CDN
@ -182,7 +183,7 @@ import { createCache } from 'axios-cache-interceptor';
``` ```
```js ```js
const { createCache } = window.AxiosCacheInterceptor; const { setupCache } = window.AxiosCacheInterceptor;
``` ```
<br /> <br />
@ -197,9 +198,9 @@ by axios was it's types.**
| [Version](https://github.com/ArthurFiorette/axios-cache-interceptor/releases) | [Axios](https://github.com/axios/axios/releases) | | [Version](https://github.com/ArthurFiorette/axios-cache-interceptor/releases) | [Axios](https://github.com/axios/axios/releases) |
| ----------------------------------------------------------------------------- | ------------------------------------------------ | | ----------------------------------------------------------------------------- | ------------------------------------------------ |
| `>= v0.5` | `>= v0.24` | | `>= v0.5` | `>= v0.24` |
| `~ v0.4` | `>= v0.23` | | `~ v0.4` | `>= v0.23` |
| `~ v0.3` | `>= v0.22` | | `~ v0.3` | `>= v0.22` |
| `<= v0.2` | `v0.21` | | `<= v0.2` | `v0.21` |
<br /> <br />
@ -210,35 +211,37 @@ To you use this cache interceptor, you can apply to an existing instance or crea
one. one.
```js ```js
import { createCache } from 'axios-cache-interceptor'; import { setupCache } from 'axios-cache-interceptor';
// Your axios instance // Your axios instance
let axios; let axios;
// Return the same axios instance, but with a modified Typescript type. // Return the same axios instance, but with a modified Typescript type.
axios = createCache(axios, { axios = setupCache(axios, {
/* options here */ /* options here */
}); });
``` ```
After that, you can made your own requests normally, as this library respects axios API. After that, you can made your own requests normally, as this library respects axios API.
Afterwards, the only thing you may need to configure is per-request configuration, you can change them with the `cache` property. Afterwards, the only thing you may need to configure is per-request configuration, you can
change them with the `cache` property.
```js ```js
import { createCache } from 'axios-cache-interceptor'; import { setupCache } from 'axios-cache-interceptor';
// Your axios-cache-interceptor instance // Your axios-cache-interceptor instance
let axios; let axios;
axios.get('url', { axios.get('url', {
cache: { cache: {
/** options here */ /** Options here */
} }
}) });
``` ```
You will get syntax highlighting for all options and what they do. But you can also read here: [Per-request configuration](#per-request-configuration). You will get syntax highlighting for all options and what they do. But you can also read
here: [Per-request configuration](#per-request-configuration).
<br /> <br />
@ -257,6 +260,48 @@ the dist with lower ecma script versions.
<br /> <br />
## Typescript users
This package does not pollute the global axios typings. Instead, the `setupCache` returns
the same axios instance but with **extended** typings.
```ts
const axios = axios.create();
axios === setupCache(axios, {});
```
In this way, we recommend you to not use a global axios instance with typescript, so you
can use all exported types from `axios-cache-interceptor` by creating a new variable.
```ts
import Axios from 'axios';
import { setupCache, AxiosCacheInstance } from 'axios-cache-interceptor';
// instance will have our custom typings from the return of this function
const instance = setupCache(
Axios.create({
// Axios options
}),
{
// Axios-cache-interceptor options
}
);
// OR
const instance = axios.create({
// Axios options
}) as AxiosCacheInstance;
// As this functions returns the same axios instance but only with
// different typings, you can ignore the function return.
setupCache(instance, {
// Axios-cache-interceptor options
});
```
<br />
## Basic Knowledge ## Basic Knowledge
### Request id ### Request id
@ -313,7 +358,7 @@ the internal code. Remember that, depending on the
When applying the interceptor, you can customize some properties: When applying the interceptor, you can customize some properties:
```js ```js
const axios = createCache(axios, { const axios = setupCache(axios, {
// Properties here // Properties here
}); });
``` ```

View File

@ -1,37 +1,28 @@
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-var-requires */
const Axios = require('axios'); const { create: createAxios } = require('axios').default;
const { createCache } = require('axios-cache-interceptor'); const { setupCache } = require('../dist');
async function main() { async function main() {
const axios = Axios.create({ const axios = setupCache(
baseUrl: 'https://api.github.com' // creating axios instance
}); createAxios({
baseUrl: 'https://registry.npmjs.org/'
}),
/** // configuring the cache
* The same instance of the previous axios, but has custom Typescript types to better intellisense {
* ttl: 99999,
* @example
*
* ```js
* axios === axiosWithCache;
* ```
*/
const axiosWithCache = createCache(axios, {
ttl: 99999,
// Parse the Cache-Control header to determine the cache strategy // Parse the Cache-Control header to determine the cache strategy
interpretHeader: true interpretHeader: true
}); }
const fetchedResponse = await axiosWithCache.get(
'https://registry.npmjs.org//axios-cache-interceptor'
); );
const fetchedResponse = await axios.get('/axios-cache-interceptor');
// This won't made a network request, because the response is already cached // This won't made a network request, because the response is already cached
const cachedResponse = await axiosWithCache.get( const cachedResponse = await axios.get('/axios-cache-interceptor');
'https://registry.npmjs.org//axios-cache-interceptor'
);
console.log('First request was cached?'); console.log('First request was cached?');
console.log(fetchedResponse.cached, '\n'); console.log(fetchedResponse.cached, '\n');
@ -45,7 +36,7 @@ async function main() {
console.log('And also the received Age header'); console.log('And also the received Age header');
console.log(fetchedResponse.headers['age'], '\n'); console.log(fetchedResponse.headers['age'], '\n');
const cacheInformation = await axiosWithCache.storage.get(fetchedResponse.id); const cacheInformation = await axios.storage.get(fetchedResponse.id);
console.log( console.log(
'As you can see, the TTL used was the maxAge cache directive minus the Age header', 'As you can see, the TTL used was the maxAge cache directive minus the Age header',
@ -59,19 +50,16 @@ async function main() {
); );
// Remove the old cache by brute force // Remove the old cache by brute force
await axiosWithCache.storage.remove(fetchedResponse.id); await axios.storage.remove(fetchedResponse.id);
const refetchedResponse = await axiosWithCache.get( const refetchedResponse = await axios.get('/axios-cache-interceptor', {
'https://registry.npmjs.org//axios-cache-interceptor', cache: {
{ // This time with interpretHeader disabled
cache: { interpretHeader: false
// This time with interpretHeader disabled
interpretHeader: false
}
} }
); });
const refetchedInformation = await axiosWithCache.storage.get(refetchedResponse.id); const refetchedInformation = await axios.storage.get(refetchedResponse.id);
console.log('Third request TTL:'); console.log('Third request TTL:');
console.log(refetchedInformation.ttl); console.log(refetchedInformation.ttl);

46
src/cache/create.ts vendored
View File

@ -12,11 +12,40 @@ export type CacheOptions = Partial<CacheInstance> & Partial<CacheProperties>;
/** /**
* Apply the caching interceptors for a already created axios instance. * Apply the caching interceptors for a already created axios instance.
* *
* @example
*
* ```ts
* import Axios from 'axios';
* import { setupCache, AxiosCacheInstance } from 'axios-cache-interceptor';
*
* // instance will have our custom typings from the return of this function
* const instance = setupCache(
* Axios.create({
* // Axios options
* }),
* {
* // Axios-cache-interceptor options
* }
* );
*
* // OR
*
* const instance = axios.create({
* // Axios options
* }) as AxiosCacheInstance;
*
* // As this functions returns the same axios instance but only with
* // different typings, you can ignore the function return.
* setupCache(instance, {
* // Axios-cache-interceptor options
* });
* ```
*
* @param axios The already created axios instance * @param axios The already created axios instance
* @param config The config for the caching interceptors * @param config The config for the caching interceptors
* @returns The same instance but with caching enabled * @returns The same instance with better typescript types.
*/ */
export function createCache( export function setupCache(
axios: AxiosInstance, axios: AxiosInstance,
{ {
storage, storage,
@ -61,12 +90,7 @@ export function createCache(
return axiosCache; return axiosCache;
} }
/** /** @deprecated */
* Apply the caching interceptors for a already created axios instance. export const useCache = setupCache as unknown as 'use setupCache instead';
* /** @deprecated */
* @deprecated Prefer {@link createCache} export const createCache = setupCache as unknown as 'use setupCache instead';
* @param axios The already created axios instance
* @param config The config for the caching interceptors
* @returns The same instance but with caching enabled
*/
export const useCache = createCache;

View File

@ -1,6 +1,6 @@
/** Index file for webpack and cdn usage */ /** Index file for webpack and cdn usage */
export { createCache, useCache } from './cache/create'; export { createCache, setupCache, useCache } from './cache/create';
export { BrowserAxiosStorage } from './storage/browser'; export { BrowserAxiosStorage } from './storage/browser';
export { MemoryAxiosStorage } from './storage/memory'; export { MemoryAxiosStorage } from './storage/memory';
export { AxiosStorage } from './storage/storage'; export { AxiosStorage } from './storage/storage';

View File

@ -85,7 +85,7 @@ export class CacheResponseInterceptor<R, D>
ttl = expirationTime || expirationTime === 0 ? expirationTime : ttl; ttl = expirationTime || expirationTime === 0 ? expirationTime : ttl;
} }
const data = CacheResponseInterceptor.createCacheData(response, cache.data); const data = CacheResponseInterceptor.setupCacheData(response, cache.data);
const newCache: CachedStorageValue = { const newCache: CachedStorageValue = {
state: 'cached', state: 'cached',
@ -135,7 +135,7 @@ export class CacheResponseInterceptor<R, D>
* Creates the new date to the cache by the provided response. Also handles possible 304 * Creates the new date to the cache by the provided response. Also handles possible 304
* Not Modified by updating response properties. * Not Modified by updating response properties.
*/ */
static readonly createCacheData = <R, D>( static readonly setupCacheData = <R, D>(
response: CacheAxiosResponse<R, D>, response: CacheAxiosResponse<R, D>,
cache?: CachedResponse cache?: CachedResponse
): CachedResponse => { ): CachedResponse => {

View File

@ -1,4 +1,4 @@
import { createCache } from '../src/cache/create'; import { setupCache } from '../src/cache/create';
import { BrowserAxiosStorage } from '../src/storage/browser'; import { BrowserAxiosStorage } from '../src/storage/browser';
import { MemoryAxiosStorage } from '../src/storage/memory'; import { MemoryAxiosStorage } from '../src/storage/memory';
import { AxiosStorage } from '../src/storage/storage'; import { AxiosStorage } from '../src/storage/storage';
@ -7,7 +7,7 @@ describe('test bundle imports', () => {
it('should have basic storages', async () => { it('should have basic storages', async () => {
const bundle = await import('../src/index.browser'); const bundle = await import('../src/index.browser');
expect(bundle.createCache).toBe(createCache); expect(bundle.setupCache).toBe(setupCache);
expect(bundle.AxiosStorage).toBe(AxiosStorage); expect(bundle.AxiosStorage).toBe(AxiosStorage);
expect(bundle.BrowserAxiosStorage).toBe(BrowserAxiosStorage); expect(bundle.BrowserAxiosStorage).toBe(BrowserAxiosStorage);
expect(bundle.MemoryAxiosStorage).toBe(MemoryAxiosStorage); expect(bundle.MemoryAxiosStorage).toBe(MemoryAxiosStorage);

View File

@ -1,13 +1,13 @@
import Axios from 'axios'; import Axios from 'axios';
import { createCache } from '../../src/cache/create'; import { setupCache } from '../../src/cache/create';
describe('tests header interpreter', () => { describe('tests header interpreter', () => {
it('tests argument composition', () => { it('tests argument composition', () => {
const axios = Axios.create(); const axios = Axios.create();
const withAxios = createCache(axios); const withAxios = setupCache(axios);
expect(withAxios).not.toBeUndefined(); expect(withAxios).not.toBeUndefined();
const withConfig = createCache(axios, { ttl: 1234 }); const withConfig = setupCache(axios, { ttl: 1234 });
expect(withConfig).not.toBeUndefined(); expect(withConfig).not.toBeUndefined();
expect(withConfig.defaults.cache.ttl).toBe(1234); expect(withConfig.defaults.cache.ttl).toBe(1234);
}); });

View File

@ -1,5 +1,5 @@
import Axios from 'axios'; import Axios from 'axios';
import { AxiosCacheInstance, CacheProperties, createCache } from '../../src'; import { AxiosCacheInstance, CacheProperties, setupCache } from '../../src';
import type { CacheInstance } from '../../src/cache/cache'; import type { CacheInstance } from '../../src/cache/cache';
import { Header } from '../../src/util/headers'; import { Header } from '../../src/util/headers';
@ -9,7 +9,7 @@ export function mockAxios(
options: Partial<CacheInstance> & Partial<CacheProperties> = {}, options: Partial<CacheInstance> & Partial<CacheProperties> = {},
responseHeaders: Record<string, string> = {} responseHeaders: Record<string, string> = {}
): AxiosCacheInstance { ): AxiosCacheInstance {
const axios = createCache(Axios.create(), options); const axios = setupCache(Axios.create(), options);
// Axios interceptors are a stack, so apply this after the cache interceptor // Axios interceptors are a stack, so apply this after the cache interceptor
axios.interceptors.request.use((config) => { axios.interceptors.request.use((config) => {