From d6b41e802fe6ac31d5c7619e7a7a69560e417029 Mon Sep 17 00:00:00 2001 From: arthurfiorette Date: Fri, 17 Feb 2023 13:16:06 -0300 Subject: [PATCH] feat: incresed tsdoc documentation a lot --- docs/src/config.md | 7 +- docs/src/config/request-specifics.md | 44 +++--- docs/src/config/response-object.md | 44 +++--- docs/src/guide/storages.md | 2 +- src/cache/axios.ts | 54 +++++-- src/cache/cache.ts | 219 ++++++++++++++++++++------- src/cache/create.ts | 32 +--- src/header/interpreter.ts | 4 +- src/header/types.ts | 26 ++-- src/index.ts | 7 +- src/storage/build.ts | 11 +- src/storage/types.ts | 23 +-- 12 files changed, 297 insertions(+), 176 deletions(-) diff --git a/docs/src/config.md b/docs/src/config.md index 4f8970a5..3edc7d52 100644 --- a/docs/src/config.md +++ b/docs/src/config.md @@ -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']); diff --git a/docs/src/config/request-specifics.md b/docs/src/config/request-specifics.md index 9c007f03..4a9ca903 100644 --- a/docs/src/config/request-specifics.md +++ b/docs/src/config/request-specifics.md @@ -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 - Type: `false` or `Partial>`. -- 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` - 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. diff --git a/docs/src/config/response-object.md b/docs/src/config/response-object.md index d5535e0d..84475cb4 100644 --- a/docs/src/config/response-object.md +++ b/docs/src/config/response-object.md @@ -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'); +## id -// response.data -// response.cached -// response.id -// ... -``` +- Type: `string` -Every response that came from our custom axios instance, will have some extras properties, -that you can retrieve like that: +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) ```ts -const result = await cache.get(/* ... */); -const id = result['propertyName']; +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` +## cached - Type: `boolean` -A simple boolean that tells you if this request came from the cache or through the -network. +A simple boolean indicating if the request returned data from the cache or from the +network call. ::: tip -This is not a boolean to check wether this request is capable of being cached or not. +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. ::: - -## `id` - -- Type: `string` - -The resolved [request id](../guide/request-id.md). This property represents the ID used -throughout the internal code. - -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). diff --git a/docs/src/guide/storages.md b/docs/src/guide/storages.md index 60037dd8..8dba2650 100644 --- a/docs/src/guide/storages.md +++ b/docs/src/guide/storages.md @@ -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 diff --git a/src/cache/axios.ts b/src/cache/axios.ts index 6b9cd869..8f82cd79 100644 --- a/src/cache/axios.ts +++ b/src/cache/axios.ts @@ -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 = AxiosResponse & { config: CacheRequestConfig; - /** 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 = AxiosResponse & { */ export type CacheRequestConfig = AxiosRequestConfig & { /** - * 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. + * + * 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. * - * False means ignore everything about cache, for this request. + * @default 'inherits from global configuration' + * @see https://axios-cache-interceptor.js.org/config/response-object#cache */ cache?: false | Partial>; }; @@ -56,9 +92,7 @@ export type InternalCacheRequestConfig = CacheRequestConfig = { * 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) => number | Promise); /** - * 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[]; /** - * 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; /** - * 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; /** - * 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 = { * 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: - * - * ```js - * const customPredicate = (response, cache, error) => { - * // Return false if has a response - * return !response; - * }; - * ``` + * **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.** * - * 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; @@ -141,6 +182,7 @@ export type CacheProperties = { * 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 = { * 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 = { ) => void | Promise); }; +/** + * 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. + * + * 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. * - * Can be used to listen when a request is cached or not. + * @default { } + * @see https://axios-cache-interceptor.js.org/config#waiting */ waiting: Record>; /** - * 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>; /** - * 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>; /** - * 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 }; diff --git a/src/cache/create.ts b/src/cache/create.ts index 21c19119..ec981dcd 100644 --- a/src/cache/create.ts +++ b/src/cache/create.ts @@ -13,38 +13,18 @@ export type CacheOptions = Partial & Partial; /** * 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, diff --git a/src/header/interpreter.ts b/src/header/interpreter.ts index 977b8260..20c7d147 100644 --- a/src/header/interpreter.ts +++ b/src/header/interpreter.ts @@ -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]; diff --git a/src/header/types.ts b/src/header/types.ts index 864b2864..850332ca 100644 --- a/src/header/types.ts +++ b/src/header/types.ts @@ -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. * - * @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 + * The possible returns are: * - * @param header The header string to interpret. + * - `'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. + * @see https://axios-cache-interceptor.js.org/config#headerinterpreter */ export type HeaderInterpreter = ( - header: string, - headers: AxiosRequestHeaders + headers?: CacheAxiosResponse['headers'] ) => InterpreterResult; diff --git a/src/index.ts b/src/index.ts index fb443697..dcfa874b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' ); } diff --git a/src/storage/build.ts b/src/storage/build.ts index e0bf9049..66ac5332 100644 --- a/src/storage/build.ts +++ b/src/storage/build.ts @@ -40,6 +40,7 @@ export type BuildStorage = Omit & { * * @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 & { }; /** - * 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 & { * * 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, diff --git a/src/storage/types.ts b/src/storage/types.ts index ee0f0c25..729b8961 100644 --- a/src/storage/types.ts +++ b/src/storage/types.ts @@ -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; @@ -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; };