feat: incresed tsdoc documentation a lot

This commit is contained in:
arthurfiorette 2023-02-17 13:16:06 -03:00
parent 384c6b59ee
commit d6b41e802f
No known key found for this signature in database
GPG Key ID: 9D190CD53C53C555
12 changed files with 307 additions and 186 deletions

View File

@ -21,7 +21,8 @@ the defaults for all requests.
- Type: `AxiosStorage` - Type: `AxiosStorage`
- Default: `buildMemoryStorage()` - 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. See the [Storages](./guide/storages.md) page for more information.
@ -82,9 +83,9 @@ The possible returns are:
::: details Example of a custom headerInterpreter ::: details Example of a custom headerInterpreter
```ts ```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']) { if (headers['x-my-custom-header']) {
const seconds = Number(headers['x-my-custom-header']); const seconds = Number(headers['x-my-custom-header']);

View File

@ -21,19 +21,22 @@ the same way you do with the [global options](../config.md).
- default: _(auto generated by the current - default: _(auto generated by the current
[key generator](../guide/request-id.md#custom-generator))_ [key generator](../guide/request-id.md#custom-generator))_
You can override the request id used by this property. The [Request ID](../guide/request-id.md) used in this request.
[See more about ids](../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)
## cache ## cache
<Badge text="optional" type="warning"/> <Badge text="optional" type="warning"/>
- Type: `false` or `Partial<CacheProperties<R, D>>`. - Type: `false` or `Partial<CacheProperties<R, D>>`.
- Default: `{}` _(Inherits from global options)_ - Default: `{}` _(Inherits from global configuration)_
::: tip ::: 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` - Type: `boolean`
- Default: `true` - 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 ::: tip
You can override the default behavior by setting the You can override the default behavior by changing the
**[headerInterpreter](../config.md#headerinterpreter)** when creating the cached axios **[headerInterpreter](../config.md#headerinterpreter)** option.
client.
::: :::
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 See the actual implementation of the
[`interpretHeader`](https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/src/header/interpreter.ts) [`interpretHeader`](https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/src/header/interpreter.ts)
method for more information. method for more information.
@ -165,7 +167,7 @@ exceptions to the method rule.
- Type: `CachePredicate<R, D>` - Type: `CachePredicate<R, D>`
- Default: `{}` - 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. cached.
```ts{5,8,13} ```ts{5,8,13}
@ -173,11 +175,11 @@ axios.get<{ auth: { status: string } }>('url', {
cache: { cache: {
cachePredicate: { cachePredicate: {
// Only cache if the response comes with a "good" status code // 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. // Tests against any header present in the response.
containsHeaders: { containsHeaders: {
'x-custom-header-3': (value) => /* some calculation */ true 'x-custom-header-3': (value) => true // some calculation
}, },
// Check custom response body // Check custom response body
@ -261,14 +263,18 @@ To use `true` (automatic ETag handling), `interpretHeader` option must be set to
- Type: `boolean` - Type: `boolean`
- Default: `true` - Default: `true`
Use `If-Modified-Since` header in this request. Use a date to force a custom static value Use
or true to use the last cached timestamp. [`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 never cached before, the header is not set.
If `interpretHeader` is set and a `Last-Modified` header is sent to us, then value from If `interpretHeader` is set and a
that header is used, otherwise cache creation timestamp will be sent in [`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified)
`If-Modified-Since`. 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 ## 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. - `number` -> the max time (in seconds) that the cache can be reused.
- `boolean` -> `false` disables and `true` enables with infinite time. - `boolean` -> `false` disables and `true` enables with infinite time.

View File

@ -1,43 +1,35 @@
# Response object # 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 ## id
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`
- Type: `string` - Type: `string`
The resolved [request id](../guide/request-id.md). This property represents the ID used The [Request ID](../guide/request-id.md) used in this request.
throughout the internal code.
Depending on the [Key Generator](../guide/request-id.md#custom-generator), it can differ It may have been generated by the [Key Generator](../guide/request-id.md#custom-generator)
from provided example on the [Request Id](../guide/request-id.md). 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.
:::

View File

@ -126,7 +126,7 @@ storages, you can use them as a base to also create your own.
- [Node Redis v4](#node-redis-v4-example) - [Node Redis v4](#node-redis-v4-example)
- **Have another one?** - **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. here.
## Node Redis Example ## Node Redis Example

54
src/cache/axios.ts vendored
View File

@ -11,16 +11,40 @@ import type {
import type { CacheInstance, CacheProperties } from './cache'; 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 R The type returned by this response
* @template D The type that the request body was * @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> & { export type CacheAxiosResponse<R = any, D = any> = AxiosResponse<R, D> & {
config: CacheRequestConfig<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; 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; 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> & { 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 * The [Request ID](https://axios-cache-interceptor.js.org/guide/request-id) used in
* with this id will be returned. * 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; 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>>; 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 * Same as the AxiosInstance but with CacheRequestConfig as a config type and
* CacheAxiosResponse as response type. * CacheAxiosResponse as response type.
* *
* @see AxiosInstance * @see https://axios-cache-interceptor.js.org/guide/getting-started
* @see CacheRequestConfig
* @see CacheInstance
*/ */
export interface AxiosCacheInstance extends CacheInstance, AxiosInstance { export interface AxiosCacheInstance extends CacheInstance, AxiosInstance {
// eslint-disable-next-line @typescript-eslint/no-misused-new // eslint-disable-next-line @typescript-eslint/no-misused-new

217
src/cache/cache.ts vendored
View File

@ -1,6 +1,6 @@
import type { Method } from 'axios'; import type { Method } from 'axios';
import type { Deferred } from 'fast-defer'; 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 { AxiosInterceptor } from '../interceptors/build';
import type { import type {
AxiosStorage, AxiosStorage,
@ -32,74 +32,122 @@ export type CacheProperties<R = unknown, D = unknown> = {
* can't determine their TTL value to override this * can't determine their TTL value to override this
* *
* @default 1000 * 60 * 5 // 5 Minutes * @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>); ttl: number | ((response: CacheAxiosResponse<R, D>) => number | Promise<number>);
/** /**
* If this interceptor should configure the cache from the request cache header When * If activated, when the response is received, the `ttl` property will be inferred from
* used, the ttl property is ignored * 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 * @default true
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-interpretheader
*/ */
interpretHeader: boolean; interpretHeader: boolean;
/** /**
* If this interceptor should include some headers in the request to tell any possible * As most of our cache strategies depends on well known defined HTTP headers, most
* adapter / client that only we should use cache mechanisms to this request. * 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 * @default true
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-cachetakeover
*/ */
cacheTakeover: boolean; 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'] * @default ['get']
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-methods
*/ */
methods: Lowercase<Method>[]; 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 } * @default { statusCheck: (status) => status >= 200 && status < 400 }
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-cachepredicate
*/ */
cachePredicate: CachePredicate<R, D>; cachePredicate: CachePredicate<R, D>;
/** /**
* Once the request is resolved, this specifies what requests should we change the * 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. * 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. * Using a function instead of an object is supported but not recommended, as it's
*
* 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
* better to just consume the response normally and write your own code after it. But * 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 {{}} * @default {{}}
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-update
*/ */
update: CacheUpdater<R, D>; update: CacheUpdater<R, D>;
/** /**
* If the request should handle `ETag` and `If-None-Match` support. Use a string to * If the request should handle
* force a custom value or true to use the response ETag * [`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 * @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; etag: string | boolean;
/** /**
* Use `If-Modified-Since` header in this request. Use a date to force a custom value or * Use
* true to use the last cached timestamp. If never cached before, the header is not * [`If-Modified-Since`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since)
* set. * 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. * @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; 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 * status code, network errors and etc. You can filter the type of error that should be
* stale by using a predicate function. * stale by using a predicate function.
* *
* **Note**: If the response is treated as error because of invalid status code _(like * **If the response is treated as error because of invalid status code _(like when
* from AxiosRequestConfig#invalidateStatus)_, and this ends up `true`, the cache will * using
* be preserved over the "invalid" request. So, if you want to preserve the response, * [statusCheck](https://axios-cache-interceptor.js.org/config/request-specifics#cache-cachepredicate))_,
* you can use this predicate: * and this ends up `true`, the cache will be preserved over the "invalid" request.**
* *
* ```js * Types:
* const customPredicate = (response, cache, error) => {
* // Return false if has a response
* return !response;
* };
* ```
*
* Possible types:
* *
* - `number` -> the max time (in seconds) that the cache can be reused. * - `number` -> the max time (in seconds) that the cache can be reused.
* - `boolean` -> `false` disables and `true` enables with infinite time. * - `boolean` -> `false` disables and `true` enables with infinite time.
* - `function` -> a predicate that can return `number` or `boolean` as described above. * - `function` -> a predicate that can return `number` or `boolean` as described above.
* *
* @default true * @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>; staleIfError: StaleIfErrorPredicate<R, D>;
@ -141,6 +182,7 @@ export type CacheProperties<R = unknown, D = unknown> = {
* options are still available and will work as expected. * options are still available and will work as expected.
* *
* @default false * @default false
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-override
*/ */
override: boolean; 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. * hydrate **IS NOT CALLED**, as the axios promise will be resolved instantly.
* *
* @default undefined * @default undefined
* @see https://axios-cache-interceptor.js.org/config/request-specifics#cache-hydrate
*/ */
hydrate: hydrate:
| undefined | undefined
@ -169,56 +212,124 @@ export type CacheProperties<R = unknown, D = unknown> = {
) => void | Promise<void>); ) => 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 { 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 * @default buildMemoryStorage
* @see https://axios-cache-interceptor.js.org/config#storage
*/ */
storage: AxiosStorage; storage: AxiosStorage;
/** /**
* The function used to create different keys for each request. Defaults to a function * 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, * that priorizes the id, and if not specified, a string is generated using the
* baseURL, params, and url * `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; 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>>; waiting: Record<string, Deferred<CachedResponse>>;
/** /**
* The function to parse and interpret response headers. Only used if * The function used to interpret all headers from a request and determine a time to
* cache.interpretHeader is true. * 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 * @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 * @default defaultRequestInterceptor
* @see https://axios-cache-interceptor.js.org/config#requestinterceptor
*/ */
requestInterceptor: AxiosInterceptor<CacheRequestConfig<unknown, unknown>>; 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 * @default defaultResponseInterceptor
* @see https://axios-cache-interceptor.js.org/config#responseinterceptor
*/ */
responseInterceptor: AxiosInterceptor<CacheAxiosResponse<unknown, unknown>>; 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 * @see https://axios-cache-interceptor.js.org/#/pages/development-mode
*/ */
debug: undefined | ((msg: DebugObject) => void); 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 * 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
View File

@ -13,38 +13,18 @@ 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 * ```ts
* import Axios from 'axios'; * const axios = setupCache(axios, OPTIONS);
* 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
* });
* ``` * ```
* *
* 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 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 with extended typescript types. * @returns The same instance with extended typescript types.
* @see https://axios-cache-interceptor.js.org/config
*/ */
export function setupCache( export function setupCache(
axios: AxiosInstance, axios: AxiosInstance,

View File

@ -1,8 +1,8 @@
import { parse } from 'cache-parser'; import { parse } from 'cache-parser';
import { Header } from './headers'; 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'; if (!headers) return 'not enough headers';
const cacheControl: unknown = headers[Header.CacheControl]; const cacheControl: unknown = headers[Header.CacheControl];

View File

@ -1,29 +1,23 @@
import type { AxiosRequestHeaders } from 'axios';
import type { CacheAxiosResponse } from '../cache/axios'; import type { CacheAxiosResponse } from '../cache/axios';
export type InterpreterResult = 'dont cache' | 'not enough headers' | number; 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. * @param header The header object to interpret.
* @returns `false` if cache should not be used. `undefined` when provided headers was not * @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 * enough to determine a valid value. Or a `number` containing the number of
* **milliseconds** to cache the response. * **milliseconds** to cache the response.
*/ * @see https://axios-cache-interceptor.js.org/config#headerinterpreter
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.
*/ */
export type HeaderInterpreter = ( export type HeaderInterpreter = (
header: string, headers?: CacheAxiosResponse['headers']
headers: AxiosRequestHeaders
) => InterpreterResult; ) => InterpreterResult;

View File

@ -20,8 +20,9 @@ export * from './util/update-cache';
/** @internal */ /** @internal */
declare global { declare global {
/** /**
* Global variable defined at compile time. Use to write code that will only be executed * **This declaration is erased at compile time.**
* at development time. *
* Use to write code that will only be executed at development time.
* *
* @internal * @internal
*/ */
@ -30,6 +31,6 @@ declare global {
if (__ACI_DEV__) { if (__ACI_DEV__) {
console.error( 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'
); );
} }

View File

@ -40,6 +40,7 @@ export type BuildStorage = Omit<AxiosStorage, 'get'> & {
* *
* @param key The key to look for * @param key The key to look for
* @param currentRequest The current {@link CacheRequestConfig}, if any * @param currentRequest The current {@link CacheRequestConfig}, if any
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
*/ */
find: ( find: (
key: string, 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. * **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 }); * const axios = setupCache(axios, { storage: myStorage });
* ``` * ```
*
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
*/ */
export function buildStorage({ set, find, remove }: BuildStorage): AxiosStorage { export function buildStorage({ set, find, remove }: BuildStorage): AxiosStorage {
return { return {
//@ts-expect-error - we don't want to expose thi //@ts-expect-error - we don't want to expose this
['is-storage']: 1, ['is-storage']: 1,
set, set,
remove, remove,

View File

@ -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** * @default buildMemoryStorage
* * @see https://axios-cache-interceptor.js.org/guide/storages
* @example
*
* ```js
* const myStorage = buildStorage({
* find: () => {...},
* set: () => {...},
* remove: () => {...}
* });
*
* const axios = setupCache(axios, { storage: myStorage });
* ```
*/ */
export type AxiosStorage = { export type AxiosStorage = {
/** /**
@ -88,6 +78,7 @@ export type AxiosStorage = {
* @param key The key to look for * @param key The key to look for
* @param value The value to save. * @param value The value to save.
* @param currentRequest The current {@link CacheRequestConfig}, if any * @param currentRequest The current {@link CacheRequestConfig}, if any
* @see https://axios-cache-interceptor.js.org/guide/storages#buildstorage
*/ */
set: ( set: (
key: string, key: string,
@ -100,6 +91,7 @@ export type AxiosStorage = {
* *
* @param key The key to look for * @param key The key to look for
* @param currentRequest The current {@link CacheRequestConfig}, if any * @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>; 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 * Returns the value for the given key. This method make checks for cache invalidation
* or etc. * 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. * storage value.
* *
* @param key The key to look for * @param key The key to look for
* @param currentRequest The current {@link CacheRequestConfig}, if any * @param currentRequest The current {@link CacheRequestConfig}, if any
* @returns The saved value for the given key. * @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>; get: (key: string, currentRequest?: CacheRequestConfig) => MaybePromise<StorageValue>;
}; };