mirror of
https://github.com/arthurfiorette/axios-cache-interceptor.git
synced 2025-12-08 17:36:16 +00:00
feat: incresed tsdoc documentation a lot
This commit is contained in:
parent
384c6b59ee
commit
d6b41e802f
@ -21,7 +21,8 @@ the defaults for all requests.
|
||||
- Type: `AxiosStorage`
|
||||
- Default: `buildMemoryStorage()`
|
||||
|
||||
The object responsible to save, retrieve and serialize (if needed) cache data.
|
||||
A storage interface is the entity responsible for saving, retrieving and serializing data
|
||||
received from network and requested when a axios call is made.
|
||||
|
||||
See the [Storages](./guide/storages.md) page for more information.
|
||||
|
||||
@ -82,9 +83,9 @@ The possible returns are:
|
||||
::: details Example of a custom headerInterpreter
|
||||
|
||||
```ts
|
||||
import { setupCache, type HeaderInterpreter } from 'axios-cache-interceptor';
|
||||
import { setupCache, type HeadersInterpreter } from 'axios-cache-interceptor';
|
||||
|
||||
const myHeaderInterpreter: HeaderInterpreter = (headers) => {
|
||||
const myHeaderInterpreter: HeadersInterpreter = (headers) => {
|
||||
if (headers['x-my-custom-header']) {
|
||||
const seconds = Number(headers['x-my-custom-header']);
|
||||
|
||||
|
||||
@ -21,19 +21,22 @@ the same way you do with the [global options](../config.md).
|
||||
- default: _(auto generated by the current
|
||||
[key generator](../guide/request-id.md#custom-generator))_
|
||||
|
||||
You can override the request id used by this property.
|
||||
[See more about ids](../guide/request-id.md).
|
||||
The [Request ID](../guide/request-id.md) used in this request.
|
||||
|
||||
It may have been generated by the [Key Generator](../guide/request-id.md#custom-generator)
|
||||
or a custom one provided by [`config.id`](./request-specifics.md#id)
|
||||
|
||||
## cache
|
||||
|
||||
<Badge text="optional" type="warning"/>
|
||||
|
||||
- Type: `false` or `Partial<CacheProperties<R, D>>`.
|
||||
- Default: `{}` _(Inherits from global options)_
|
||||
- Default: `{}` _(Inherits from global configuration)_
|
||||
|
||||
::: tip
|
||||
|
||||
This property is optional, and if not provided, the default cache properties will be used.
|
||||
As this property is optional, when not provided, all properties will inherit from global
|
||||
configuration
|
||||
|
||||
:::
|
||||
|
||||
@ -79,17 +82,16 @@ value
|
||||
- Type: `boolean`
|
||||
- Default: `true`
|
||||
|
||||
If activated, when the response is received, the `ttl` property will be inferred from the
|
||||
requests headers. As described in the MDN docs and HTML specification.
|
||||
|
||||
::: tip
|
||||
|
||||
You can override the default behavior by setting the
|
||||
**[headerInterpreter](../config.md#headerinterpreter)** when creating the cached axios
|
||||
client.
|
||||
You can override the default behavior by changing the
|
||||
**[headerInterpreter](../config.md#headerinterpreter)** option.
|
||||
|
||||
:::
|
||||
|
||||
If activated, when the response is received, the `ttl` property will be inferred from the
|
||||
requests headers. As described in the MDN docs and HTML specification.
|
||||
|
||||
See the actual implementation of the
|
||||
[`interpretHeader`](https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/src/header/interpreter.ts)
|
||||
method for more information.
|
||||
@ -165,7 +167,7 @@ exceptions to the method rule.
|
||||
- Type: `CachePredicate<R, D>`
|
||||
- Default: `{}`
|
||||
|
||||
An object or function that will be tested against the response to test if it can be
|
||||
An object or function that will be tested against the response to indicate if it can be
|
||||
cached.
|
||||
|
||||
```ts{5,8,13}
|
||||
@ -173,11 +175,11 @@ axios.get<{ auth: { status: string } }>('url', {
|
||||
cache: {
|
||||
cachePredicate: {
|
||||
// Only cache if the response comes with a "good" status code
|
||||
statusCheck: (status) => /* some calculation */ true,
|
||||
statusCheck: (status) => true, // some calculation
|
||||
|
||||
// Tests against any header present in the response.
|
||||
containsHeaders: {
|
||||
'x-custom-header-3': (value) => /* some calculation */ true
|
||||
'x-custom-header-3': (value) => true // some calculation
|
||||
},
|
||||
|
||||
// Check custom response body
|
||||
@ -261,14 +263,18 @@ To use `true` (automatic ETag handling), `interpretHeader` option must be set to
|
||||
- Type: `boolean`
|
||||
- Default: `true`
|
||||
|
||||
Use `If-Modified-Since` header in this request. Use a date to force a custom static value
|
||||
or true to use the last cached timestamp.
|
||||
Use
|
||||
[`If-Modified-Since`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since)
|
||||
header in this request. Use a date to force a custom static value or true to use the last
|
||||
cached timestamp.
|
||||
|
||||
If never cached before, the header is not set.
|
||||
|
||||
If `interpretHeader` is set and a `Last-Modified` header is sent to us, then value from
|
||||
that header is used, otherwise cache creation timestamp will be sent in
|
||||
`If-Modified-Since`.
|
||||
If `interpretHeader` is set and a
|
||||
[`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified)
|
||||
header is sent to us, then value from that header is used, otherwise cache creation
|
||||
timestamp will be sent in
|
||||
[`If-Modified-Since`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since).
|
||||
|
||||
## cache.staleIfError
|
||||
|
||||
@ -299,7 +305,7 @@ const customPredicate = (response, cache, error) => {
|
||||
};
|
||||
```
|
||||
|
||||
Types Explanations
|
||||
Types:
|
||||
|
||||
- `number` -> the max time (in seconds) that the cache can be reused.
|
||||
- `boolean` -> `false` disables and `true` enables with infinite time.
|
||||
|
||||
@ -1,43 +1,35 @@
|
||||
# Response object
|
||||
|
||||
Every response that came from our custom axios instance will have some extras properties.
|
||||
Axios cache interceptor returns a slightly changed than the original axios response.
|
||||
Containing information about the cache and other needed properties.
|
||||
|
||||
```ts
|
||||
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
|
||||
|
||||
// response.data
|
||||
// response.cached
|
||||
// response.id
|
||||
// ...
|
||||
```
|
||||
|
||||
Every response that came from our custom axios instance, will have some extras properties,
|
||||
that you can retrieve like that:
|
||||
|
||||
```ts
|
||||
const result = await cache.get(/* ... */);
|
||||
const id = result['propertyName'];
|
||||
```
|
||||
|
||||
## `cached`
|
||||
|
||||
- Type: `boolean`
|
||||
|
||||
A simple boolean that tells you if this request came from the cache or through the
|
||||
network.
|
||||
|
||||
::: tip
|
||||
|
||||
This is not a boolean to check wether this request is capable of being cached or not.
|
||||
|
||||
:::
|
||||
|
||||
## `id`
|
||||
## id
|
||||
|
||||
- Type: `string`
|
||||
|
||||
The resolved [request id](../guide/request-id.md). This property represents the ID used
|
||||
throughout the internal code.
|
||||
The [Request ID](../guide/request-id.md) used in this request.
|
||||
|
||||
Depending on the [Key Generator](../guide/request-id.md#custom-generator), it can differ
|
||||
from provided example on the [Request Id](../guide/request-id.md).
|
||||
It may have been generated by the [Key Generator](../guide/request-id.md#custom-generator)
|
||||
or a custom one provided by [`config.id`](./request-specifics.md#id)
|
||||
|
||||
```ts
|
||||
const response = await axios.get('url', { id: 'my-overridden-id' });
|
||||
|
||||
// This request used 'my-overridden-id' and
|
||||
// not the one generated by the key generator
|
||||
response.id === 'my-overridden-id';
|
||||
```
|
||||
|
||||
## cached
|
||||
|
||||
- Type: `boolean`
|
||||
|
||||
A simple boolean indicating if the request returned data from the cache or from the
|
||||
network call.
|
||||
|
||||
::: tip
|
||||
|
||||
This does not indicated if the request was capable of being cached or not, as options like
|
||||
[`cache.override`](./request-specifics.md#cache-override) may have been enabled.
|
||||
|
||||
:::
|
||||
|
||||
@ -126,7 +126,7 @@ storages, you can use them as a base to also create your own.
|
||||
|
||||
- [Node Redis v4](#node-redis-v4-example)
|
||||
- **Have another one?**
|
||||
[Open a PR](https://github.com/arthurfiorette/axios-cache-interceptor/pulls) to add it
|
||||
- [Open a PR](https://github.com/arthurfiorette/axios-cache-interceptor/pulls) to add it
|
||||
here.
|
||||
|
||||
## Node Redis Example
|
||||
|
||||
54
src/cache/axios.ts
vendored
54
src/cache/axios.ts
vendored
@ -11,16 +11,40 @@ import type {
|
||||
import type { CacheInstance, CacheProperties } from './cache';
|
||||
|
||||
/**
|
||||
* A slightly changed than the original axios response. Containing information about the
|
||||
* cache and other needed properties.
|
||||
*
|
||||
* @template R The type returned by this response
|
||||
* @template D The type that the request body was
|
||||
* @see https://axios-cache-interceptor.js.org/config/response-object
|
||||
*/
|
||||
export type CacheAxiosResponse<R = any, D = any> = AxiosResponse<R, D> & {
|
||||
config: CacheRequestConfig<R, D>;
|
||||
|
||||
/** The id used for this request. if config specified an id, the id will be returned */
|
||||
/**
|
||||
* The [Request ID](https://axios-cache-interceptor.js.org/guide/request-id) used in
|
||||
* this request.
|
||||
*
|
||||
* It may have been generated by the [Key
|
||||
* Generator](https://axios-cache-interceptor.js.org/guide/request-id#custom-generator)
|
||||
* or a custom one provided by
|
||||
* [`config.id`](https://axios-cache-interceptor.js.org/config/request-specifics#id)
|
||||
*
|
||||
* @see https://axios-cache-interceptor.js.org/config/response-object#id
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/** A simple boolean to check whether this request was cached or not */
|
||||
/**
|
||||
* A simple boolean indicating if the request returned data from the cache or from the
|
||||
* network call.
|
||||
*
|
||||
* This does not indicated if the request was capable of being cached or not, as options
|
||||
* like
|
||||
* [`cache.override`](https://axios-cache-interceptor.js.org/config/request-specifics#cache-override)
|
||||
* may have been enabled.
|
||||
*
|
||||
* @see https://axios-cache-interceptor.js.org/config/response-object#cached
|
||||
*/
|
||||
cached: boolean;
|
||||
};
|
||||
|
||||
@ -32,17 +56,29 @@ export type CacheAxiosResponse<R = any, D = any> = AxiosResponse<R, D> & {
|
||||
*/
|
||||
export type CacheRequestConfig<R = any, D = any> = AxiosRequestConfig<D> & {
|
||||
/**
|
||||
* An id for this request, if this request is used in cache, only the last request made
|
||||
* with this id will be returned.
|
||||
* The [Request ID](https://axios-cache-interceptor.js.org/guide/request-id) used in
|
||||
* this request.
|
||||
*
|
||||
* @default undefined
|
||||
* It may have been generated by the [Key
|
||||
* Generator](https://axios-cache-interceptor.js.org/guide/request-id#custom-generator)
|
||||
* or a custom one provided by
|
||||
* [`config.id`](https://axios-cache-interceptor.js.org/config/request-specifics#id)
|
||||
*
|
||||
* @default 'auto generated by the current key generator'
|
||||
* @see https://axios-cache-interceptor.js.org/config/response-object#id
|
||||
*/
|
||||
id?: string;
|
||||
|
||||
/**
|
||||
* All cache options for the request.
|
||||
* The cache option available through the request config is where all the cache
|
||||
* customization happens.
|
||||
*
|
||||
* False means ignore everything about cache, for this request.
|
||||
* Setting the `cache` property to `false` will disable the cache for this request.
|
||||
*
|
||||
* This does not mean that the current cache will be excluded from the storage.
|
||||
*
|
||||
* @default 'inherits from global configuration'
|
||||
* @see https://axios-cache-interceptor.js.org/config/response-object#cache
|
||||
*/
|
||||
cache?: false | Partial<CacheProperties<R, D>>;
|
||||
};
|
||||
@ -56,9 +92,7 @@ export type InternalCacheRequestConfig<R = any, D = any> = CacheRequestConfig<R,
|
||||
* Same as the AxiosInstance but with CacheRequestConfig as a config type and
|
||||
* CacheAxiosResponse as response type.
|
||||
*
|
||||
* @see AxiosInstance
|
||||
* @see CacheRequestConfig
|
||||
* @see CacheInstance
|
||||
* @see https://axios-cache-interceptor.js.org/guide/getting-started
|
||||
*/
|
||||
export interface AxiosCacheInstance extends CacheInstance, AxiosInstance {
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-new
|
||||
|
||||
217
src/cache/cache.ts
vendored
217
src/cache/cache.ts
vendored
@ -1,6 +1,6 @@
|
||||
import type { Method } from 'axios';
|
||||
import type { Deferred } from 'fast-defer';
|
||||
import type { HeadersInterpreter } from '../header/types';
|
||||
import type { HeaderInterpreter } from '../header/types';
|
||||
import type { AxiosInterceptor } from '../interceptors/build';
|
||||
import type {
|
||||
AxiosStorage,
|
||||
@ -32,74 +32,122 @@ export type CacheProperties<R = unknown, D = unknown> = {
|
||||
* can't determine their TTL value to override this
|
||||
*
|
||||
* @default 1000 * 60 * 5 // 5 Minutes
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-ttl
|
||||
*/
|
||||
ttl: number | ((response: CacheAxiosResponse<R, D>) => number | Promise<number>);
|
||||
|
||||
/**
|
||||
* If this interceptor should configure the cache from the request cache header When
|
||||
* used, the ttl property is ignored
|
||||
* If activated, when the response is received, the `ttl` property will be inferred from
|
||||
* the requests headers. As described in the MDN docs and HTML specification.
|
||||
*
|
||||
* See the actual implementation of the
|
||||
* [`interpretHeader`](https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/src/header/interpreter.ts)
|
||||
* method for more information.
|
||||
*
|
||||
* @default true
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-interpretheader
|
||||
*/
|
||||
interpretHeader: boolean;
|
||||
|
||||
/**
|
||||
* If this interceptor should include some headers in the request to tell any possible
|
||||
* adapter / client that only we should use cache mechanisms to this request.
|
||||
* As most of our cache strategies depends on well known defined HTTP headers, most
|
||||
* browsers also use those headers to define their own cache strategies and storages.
|
||||
*
|
||||
* When your requested routes includes `Cache-Control` in their responses, you may end
|
||||
* up with we and your browser caching the response, resulting in a **double layer of
|
||||
* cache**.
|
||||
*
|
||||
* This option solves this by including some predefined headers in the request, that
|
||||
* should tell any client / adapter to not cache the response, thus only we will cache
|
||||
* it.
|
||||
*
|
||||
* _These are headers used in our specific request, it won't affect any other request or
|
||||
* response that the server may handle._*
|
||||
*
|
||||
* Headers included:
|
||||
*
|
||||
* - `Cache-Control: no-cache`
|
||||
* - `Pragma: no-cache`
|
||||
* - `Expires: 0`
|
||||
*
|
||||
* Learn more at
|
||||
* [#437](https://github.com/arthurfiorette/axios-cache-interceptor/issues/437#issuecomment-1361262194)
|
||||
* and in this [StackOverflow](https://stackoverflow.com/a/62781874/14681561) answer.
|
||||
*
|
||||
* @default true
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-cachetakeover
|
||||
*/
|
||||
cacheTakeover: boolean;
|
||||
|
||||
/**
|
||||
* All methods that should be cached.
|
||||
* Specifies which methods we should handle and cache. This is where you can enable
|
||||
* caching to `POST`, `PUT`, `DELETE` and other methods, as the default is only `GET`.
|
||||
*
|
||||
* We use `methods` in a per-request configuration setup because sometimes you have
|
||||
* exceptions to the method rule.
|
||||
*
|
||||
* @default ['get']
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-methods
|
||||
*/
|
||||
methods: Lowercase<Method>[];
|
||||
|
||||
/**
|
||||
* The function to check if the response code permit being cached.
|
||||
* An object or function that will be tested against the response to indicate if it can
|
||||
* be cached.
|
||||
*
|
||||
* @default { statusCheck: (status) => status >= 200 && status < 400 }
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-cachepredicate
|
||||
*/
|
||||
cachePredicate: CachePredicate<R, D>;
|
||||
|
||||
/**
|
||||
* Once the request is resolved, this specifies what requests should we change the
|
||||
* cache. Can be used to update the request or delete other caches.
|
||||
* Once the request is resolved, this specifies what other responses should change their
|
||||
* cache. Can be used to update the request or delete other caches. It is a simple
|
||||
* `Record` with the request id.
|
||||
*
|
||||
* This is independent if the request made was cached or not.
|
||||
* Here's an example with some basic login:
|
||||
*
|
||||
* If an provided id represents and loading cache, he will be ignored.
|
||||
*
|
||||
* The id used is the same as the id on `CacheRequestConfig['id']`, auto-generated or
|
||||
* not.
|
||||
*
|
||||
* **Using a function instead of an object is supported but not recommended, as it's
|
||||
* Using a function instead of an object is supported but not recommended, as it's
|
||||
* better to just consume the response normally and write your own code after it. But
|
||||
* it`s here in case you need it.**
|
||||
* it`s here in case you need it.
|
||||
*
|
||||
* @default {{}}
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-update
|
||||
*/
|
||||
update: CacheUpdater<R, D>;
|
||||
|
||||
/**
|
||||
* If the request should handle `ETag` and `If-None-Match` support. Use a string to
|
||||
* force a custom value or true to use the response ETag
|
||||
* If the request should handle
|
||||
* [`ETag`](https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Headers/ETag) and
|
||||
* [`If-None-Match
|
||||
* support`](https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Headers/If-None-Match).
|
||||
* Use a string to force a custom static value or true to use the previous response
|
||||
* ETag.
|
||||
*
|
||||
* To use `true` (automatic ETag handling), `interpretHeader` option must be set to
|
||||
* `true`.
|
||||
*
|
||||
* @default true
|
||||
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-etag
|
||||
*/
|
||||
etag: string | boolean;
|
||||
|
||||
/**
|
||||
* Use `If-Modified-Since` header in this request. Use a date to force a custom value or
|
||||
* true to use the last cached timestamp. If never cached before, the header is not
|
||||
* set.
|
||||
* Use
|
||||
* [`If-Modified-Since`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since)
|
||||
* header in this request. Use a date to force a custom static value or true to use the
|
||||
* last cached timestamp.
|
||||
*
|
||||
* If never cached before, the header is not set.
|
||||
*
|
||||
* If `interpretHeader` is set and a
|
||||
* [`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified)
|
||||
* header is sent to us, then value from that header is used, otherwise cache creation
|
||||
* timestamp will be sent in
|
||||
* [`If-Modified-Since`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since).
|
||||
*
|
||||
* @default false // The opposite of the resulting `etag` option.
|
||||
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-modifiedsince
|
||||
*/
|
||||
modifiedSince: Date | boolean;
|
||||
|
||||
@ -108,26 +156,19 @@ export type CacheProperties<R = unknown, D = unknown> = {
|
||||
* status code, network errors and etc. You can filter the type of error that should be
|
||||
* stale by using a predicate function.
|
||||
*
|
||||
* **Note**: If the response is treated as error because of invalid status code _(like
|
||||
* from AxiosRequestConfig#invalidateStatus)_, and this ends up `true`, the cache will
|
||||
* be preserved over the "invalid" request. So, if you want to preserve the response,
|
||||
* you can use this predicate:
|
||||
* **If the response is treated as error because of invalid status code _(like when
|
||||
* using
|
||||
* [statusCheck](https://axios-cache-interceptor.js.org/config/request-specifics#cache-cachepredicate))_,
|
||||
* and this ends up `true`, the cache will be preserved over the "invalid" request.**
|
||||
*
|
||||
* ```js
|
||||
* const customPredicate = (response, cache, error) => {
|
||||
* // Return false if has a response
|
||||
* return !response;
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* Possible types:
|
||||
* Types:
|
||||
*
|
||||
* - `number` -> the max time (in seconds) that the cache can be reused.
|
||||
* - `boolean` -> `false` disables and `true` enables with infinite time.
|
||||
* - `function` -> a predicate that can return `number` or `boolean` as described above.
|
||||
*
|
||||
* @default true
|
||||
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error
|
||||
*/
|
||||
staleIfError: StaleIfErrorPredicate<R, D>;
|
||||
|
||||
@ -141,6 +182,7 @@ export type CacheProperties<R = unknown, D = unknown> = {
|
||||
* options are still available and will work as expected.
|
||||
*
|
||||
* @default false
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-override
|
||||
*/
|
||||
override: boolean;
|
||||
|
||||
@ -158,6 +200,7 @@ export type CacheProperties<R = unknown, D = unknown> = {
|
||||
* hydrate **IS NOT CALLED**, as the axios promise will be resolved instantly.
|
||||
*
|
||||
* @default undefined
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-hydrate
|
||||
*/
|
||||
hydrate:
|
||||
| undefined
|
||||
@ -169,56 +212,124 @@ export type CacheProperties<R = unknown, D = unknown> = {
|
||||
) => void | Promise<void>);
|
||||
};
|
||||
|
||||
/**
|
||||
* These are properties that are used and shared by the entire application.
|
||||
*
|
||||
* ```ts
|
||||
* const axios = setupCache(axios, OPTIONS);
|
||||
* ```
|
||||
*
|
||||
* The `setupCache` function receives global options and all [request
|
||||
* specifics](https://axios-cache-interceptor.js.org/config/request-specifics) ones too.
|
||||
* This way, you can customize the defaults for all requests.
|
||||
*
|
||||
* @see https://axios-cache-interceptor.js.org/config/request-specifics
|
||||
*/
|
||||
export interface CacheInstance {
|
||||
/**
|
||||
* The storage to save the cache data. Defaults to an in-memory storage.
|
||||
* A storage interface is the entity responsible for saving, retrieving and serializing
|
||||
* data received from network and requested when a axios call is made.
|
||||
*
|
||||
* See the [Storages](https://axios-cache-interceptor.js.org/guide/storages) page for
|
||||
* more information.
|
||||
*
|
||||
* @default buildMemoryStorage
|
||||
* @see https://axios-cache-interceptor.js.org/config#storage
|
||||
*/
|
||||
storage: AxiosStorage;
|
||||
|
||||
/**
|
||||
* The function used to create different keys for each request. Defaults to a function
|
||||
* that priorizes the id, and if not specified, a string is generated using the method,
|
||||
* baseURL, params, and url
|
||||
* that priorizes the id, and if not specified, a string is generated using the
|
||||
* `method`, `baseURL`, `params`, `data` and `url`.
|
||||
*
|
||||
* You can learn on how to use them on the [Request
|
||||
* ID](https://axios-cache-interceptor.js.org/guide/request-id#custom-generator) page.
|
||||
*
|
||||
* @default defaultKeyGenerator
|
||||
* @see https://axios-cache-interceptor.js.org/config#generatekey
|
||||
*/
|
||||
generateKey: KeyGenerator;
|
||||
|
||||
/**
|
||||
* A simple object that holds all deferred objects until it is resolved or rejected.
|
||||
* A simple object that will hold a promise for each pending request. Used to handle
|
||||
* concurrent requests.
|
||||
*
|
||||
* Can be used to listen when a request is cached or not.
|
||||
* You'd normally not need to change this, but it is exposed in case you need to use it
|
||||
* as some sort of listener of know when a request is waiting for other to finish.
|
||||
*
|
||||
* @default { }
|
||||
* @see https://axios-cache-interceptor.js.org/config#waiting
|
||||
*/
|
||||
waiting: Record<string, Deferred<CachedResponse>>;
|
||||
|
||||
/**
|
||||
* The function to parse and interpret response headers. Only used if
|
||||
* cache.interpretHeader is true.
|
||||
* The function used to interpret all headers from a request and determine a time to
|
||||
* live (`ttl`) number.
|
||||
*
|
||||
* **Many REST backends returns some variation of `Cache-Control: no-cache` or
|
||||
* `Cache-Control: no-store` headers, which tell us to ignore caching at all. You shall
|
||||
* disable `headerInterpreter` for those requests.**
|
||||
*
|
||||
* **If the debug mode prints `Cache header interpreted as 'dont cache'` this is
|
||||
* probably the reason.**
|
||||
*
|
||||
* The possible returns are:
|
||||
*
|
||||
* - `'dont cache'`: the request will not be cached.
|
||||
* - `'not enough headers'`: the request will find other ways to determine the TTL value.
|
||||
* - `number`: used as the TTL value.
|
||||
*
|
||||
* @default defaultHeaderInterpreter
|
||||
* @see https://axios-cache-interceptor.js.org/config#headerinterpreter
|
||||
*/
|
||||
headerInterpreter: HeadersInterpreter;
|
||||
headerInterpreter: HeaderInterpreter;
|
||||
|
||||
/**
|
||||
* The request interceptor that will be used to handle the cache.
|
||||
* The function that will be used to intercept the request before it is sent to the
|
||||
* axios adapter.
|
||||
*
|
||||
* It is the main function of this library, as it is the bridge between the axios
|
||||
* request and the cache.
|
||||
*
|
||||
* _It wasn't meant to be changed, but if you need to, you can do it by passing a new
|
||||
* function to this property._*
|
||||
*
|
||||
* See its code for more information
|
||||
* [here](https://github.com/arthurfiorette/axios-cache-interceptor/tree/main/src/interceptors).
|
||||
*
|
||||
* @default defaultRequestInterceptor
|
||||
* @see https://axios-cache-interceptor.js.org/config#requestinterceptor
|
||||
*/
|
||||
requestInterceptor: AxiosInterceptor<CacheRequestConfig<unknown, unknown>>;
|
||||
|
||||
/**
|
||||
* The response interceptor that will be used to handle the cache.
|
||||
* The function that will be used to intercept the request after it is returned by the
|
||||
* axios adapter.
|
||||
*
|
||||
* It is the second most important function of this library, as it is the bridge between
|
||||
* the axios response and the cache.
|
||||
*
|
||||
* _It wasn't meant to be changed, but if you need to, you can do it by passing a new
|
||||
* function to this property._*
|
||||
*
|
||||
* See its code for more information
|
||||
* [here](https://github.com/arthurfiorette/axios-cache-interceptor/tree/main/src/interceptors).
|
||||
*
|
||||
* @default defaultResponseInterceptor
|
||||
* @see https://axios-cache-interceptor.js.org/config#responseinterceptor
|
||||
*/
|
||||
responseInterceptor: AxiosInterceptor<CacheAxiosResponse<unknown, unknown>>;
|
||||
|
||||
/**
|
||||
* Logs useful information in the console
|
||||
* The debug option will print debug information in the console. It is good if you need
|
||||
* to trace any undesired behavior or issue. You can enable it by setting `debug` to a
|
||||
* function that receives an string and returns nothing.
|
||||
*
|
||||
* **Note**: This is only available with development mode enabled
|
||||
* Read the [Debugging](https://axios-cache-interceptor.js.org/guide/debugging) page for
|
||||
* the complete guide.
|
||||
*
|
||||
* @default {console.log}
|
||||
* @default undefined
|
||||
* @see https://axios-cache-interceptor.js.org/#/pages/development-mode
|
||||
*/
|
||||
debug: undefined | ((msg: DebugObject) => void);
|
||||
@ -226,6 +337,8 @@ export interface CacheInstance {
|
||||
|
||||
/**
|
||||
* An object with any possible type that can be used to log and debug information in
|
||||
* `development` mode (a.k.a `__ACI_DEV__ === true`)
|
||||
* `development` mode _(a.k.a `__ACI_DEV__ === true`)_
|
||||
*
|
||||
* @see https://axios-cache-interceptor.js.org/#/pages/development-mode
|
||||
*/
|
||||
export type DebugObject = Partial<{ id: string; msg: string; data: unknown }>;
|
||||
export type DebugObject = { id?: string; msg?: string; data?: unknown };
|
||||
|
||||
32
src/cache/create.ts
vendored
32
src/cache/create.ts
vendored
@ -13,38 +13,18 @@ export type CacheOptions = Partial<CacheInstance> & Partial<CacheProperties>;
|
||||
/**
|
||||
* Apply the caching interceptors for a already created axios instance.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* import Axios from 'axios';
|
||||
* import { AxiosCacheInstance, setupCache } 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
|
||||
* });
|
||||
* const axios = setupCache(axios, OPTIONS);
|
||||
* ```
|
||||
*
|
||||
* The `setupCache` function receives global options and all [request
|
||||
* specifics](https://axios-cache-interceptor.js.org/config/request-specifics) ones too.
|
||||
* This way, you can customize the defaults for all requests.
|
||||
*
|
||||
* @param axios The already created axios instance
|
||||
* @param config The config for the caching interceptors
|
||||
* @returns The same instance with extended typescript types.
|
||||
* @see https://axios-cache-interceptor.js.org/config
|
||||
*/
|
||||
export function setupCache(
|
||||
axios: AxiosInstance,
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { parse } from 'cache-parser';
|
||||
import { Header } from './headers';
|
||||
import type { HeadersInterpreter } from './types';
|
||||
import type { HeaderInterpreter } from './types';
|
||||
|
||||
export const defaultHeaderInterpreter: HeadersInterpreter = (headers) => {
|
||||
export const defaultHeaderInterpreter: HeaderInterpreter = (headers) => {
|
||||
if (!headers) return 'not enough headers';
|
||||
|
||||
const cacheControl: unknown = headers[Header.CacheControl];
|
||||
|
||||
@ -1,29 +1,23 @@
|
||||
import type { AxiosRequestHeaders } from 'axios';
|
||||
import type { CacheAxiosResponse } from '../cache/axios';
|
||||
|
||||
export type InterpreterResult = 'dont cache' | 'not enough headers' | number;
|
||||
|
||||
/**
|
||||
* Interpret all http headers to determina a time to live.
|
||||
* - If activated, when the response is received, the `ttl` property will be inferred from
|
||||
* the requests headers. As described in the MDN docs and HTML specification.
|
||||
*
|
||||
* The possible returns are:
|
||||
*
|
||||
* - `'dont cache'`: the request will not be cached.
|
||||
* - `'not enough headers'`: the request will find other ways to determine the TTL value.
|
||||
* - `number`: used as the TTL value.
|
||||
*
|
||||
* @param header The header object to interpret.
|
||||
* @returns `false` if cache should not be used. `undefined` when provided headers was not
|
||||
* enough to determine a valid value. Or a `number` containing the number of
|
||||
* **milliseconds** to cache the response.
|
||||
*/
|
||||
export type HeadersInterpreter = (
|
||||
headers?: CacheAxiosResponse['headers']
|
||||
) => InterpreterResult;
|
||||
|
||||
/**
|
||||
* Interpret a single string header
|
||||
*
|
||||
* @param header The header string to interpret.
|
||||
* @returns `false` if cache should not be used. `undefined` when provided headers was not
|
||||
* enough to determine a valid value. Or a `number` containing the number of
|
||||
* **milliseconds** to cache the response.
|
||||
* @see https://axios-cache-interceptor.js.org/config#headerinterpreter
|
||||
*/
|
||||
export type HeaderInterpreter = (
|
||||
header: string,
|
||||
headers: AxiosRequestHeaders
|
||||
headers?: CacheAxiosResponse['headers']
|
||||
) => InterpreterResult;
|
||||
|
||||
@ -20,8 +20,9 @@ export * from './util/update-cache';
|
||||
/** @internal */
|
||||
declare global {
|
||||
/**
|
||||
* Global variable defined at compile time. Use to write code that will only be executed
|
||||
* at development time.
|
||||
* **This declaration is erased at compile time.**
|
||||
*
|
||||
* Use to write code that will only be executed at development time.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
@ -30,6 +31,6 @@ declare global {
|
||||
|
||||
if (__ACI_DEV__) {
|
||||
console.error(
|
||||
'You are using a development build. Make sure to use the correct build in production\nhttps://axios-cache-interceptor.js.org/#/pages/installing\n\n'
|
||||
'You are using a development build. Make sure to use the correct build in production\nhttps://axios-cache-interceptor.js.org/guide/getting-started\n\n'
|
||||
);
|
||||
}
|
||||
|
||||
@ -40,6 +40,7 @@ export type BuildStorage = Omit<AxiosStorage, 'get'> & {
|
||||
*
|
||||
* @param key The key to look for
|
||||
* @param currentRequest The current {@link CacheRequestConfig}, if any
|
||||
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
|
||||
*/
|
||||
find: (
|
||||
key: string,
|
||||
@ -48,7 +49,11 @@ export type BuildStorage = Omit<AxiosStorage, 'get'> & {
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds a custom storage.
|
||||
* All integrated storages are wrappers around the `buildStorage` function. External
|
||||
* libraries use it and if you want to build your own, `buildStorage` is the way to go!
|
||||
*
|
||||
* The exported `buildStorage` function abstracts the storage interface and requires a
|
||||
* super simple object to build the storage.
|
||||
*
|
||||
* **Note**: You can only create an custom storage with this function.
|
||||
*
|
||||
@ -63,10 +68,12 @@ export type BuildStorage = Omit<AxiosStorage, 'get'> & {
|
||||
*
|
||||
* const axios = setupCache(axios, { storage: myStorage });
|
||||
* ```
|
||||
*
|
||||
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
|
||||
*/
|
||||
export function buildStorage({ set, find, remove }: BuildStorage): AxiosStorage {
|
||||
return {
|
||||
//@ts-expect-error - we don't want to expose thi
|
||||
//@ts-expect-error - we don't want to expose this
|
||||
['is-storage']: 1,
|
||||
set,
|
||||
remove,
|
||||
|
||||
@ -63,21 +63,11 @@ export type EmptyStorageValue = {
|
||||
};
|
||||
|
||||
/**
|
||||
* A storage implementation that stores data in memory.
|
||||
* A storage interface is the entity responsible for saving, retrieving and serializing
|
||||
* data received from network and requested when a axios call is made.
|
||||
*
|
||||
* **You can create yours with {@link buildStorage} function**
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* const myStorage = buildStorage({
|
||||
* find: () => {...},
|
||||
* set: () => {...},
|
||||
* remove: () => {...}
|
||||
* });
|
||||
*
|
||||
* const axios = setupCache(axios, { storage: myStorage });
|
||||
* ```
|
||||
* @default buildMemoryStorage
|
||||
* @see https://axios-cache-interceptor.js.org/guide/storages
|
||||
*/
|
||||
export type AxiosStorage = {
|
||||
/**
|
||||
@ -88,6 +78,7 @@ export type AxiosStorage = {
|
||||
* @param key The key to look for
|
||||
* @param value The value to save.
|
||||
* @param currentRequest The current {@link CacheRequestConfig}, if any
|
||||
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
|
||||
*/
|
||||
set: (
|
||||
key: string,
|
||||
@ -100,6 +91,7 @@ export type AxiosStorage = {
|
||||
*
|
||||
* @param key The key to look for
|
||||
* @param currentRequest The current {@link CacheRequestConfig}, if any
|
||||
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
|
||||
*/
|
||||
remove: (key: string, currentRequest?: CacheRequestConfig) => MaybePromise<void>;
|
||||
|
||||
@ -107,12 +99,13 @@ export type AxiosStorage = {
|
||||
* Returns the value for the given key. This method make checks for cache invalidation
|
||||
* or etc.
|
||||
*
|
||||
* If the provided `find()` method returned null, this will map it to a `'empty'`
|
||||
* If the internal `find()` method returned null, this will map it to a `'empty'`
|
||||
* storage value.
|
||||
*
|
||||
* @param key The key to look for
|
||||
* @param currentRequest The current {@link CacheRequestConfig}, if any
|
||||
* @returns The saved value for the given key.
|
||||
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
|
||||
*/
|
||||
get: (key: string, currentRequest?: CacheRequestConfig) => MaybePromise<StorageValue>;
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user