Socket
Socket
Sign inDemoInstall

axios-cache-interceptor

Package Overview
Dependencies
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

axios-cache-interceptor - npm Package Compare versions

Comparing version 0.3.0 to 0.4.0

dist/cache/axios.d.ts

6

dist/index.d.ts

@@ -1,8 +0,8 @@

export * from './axios/cache';
export * from './axios/types';
export * from './cache/axios';
export * from './cache/cache';
export * from './cache/create';
export * from './header/types';
export * from './interceptors/types';
export * from './storage/types';
export * as StatusCodes from './util/status-codes';
export * from './util/types';
//# sourceMappingURL=index.d.ts.map

@@ -9,26 +9,13 @@ "use strict";

}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatusCodes = void 0;
__exportStar(require("./axios/cache"), exports);
__exportStar(require("./axios/types"), exports);
__exportStar(require("./cache/axios"), exports);
__exportStar(require("./cache/cache"), exports);
__exportStar(require("./cache/create"), exports);
__exportStar(require("./header/types"), exports);
__exportStar(require("./interceptors/types"), exports);
__exportStar(require("./storage/types"), exports);
exports.StatusCodes = __importStar(require("./util/status-codes"));
__exportStar(require("./util/types"), exports);
//# sourceMappingURL=index.js.map

@@ -1,9 +0,9 @@

import type { AxiosCacheInstance, CacheRequestConfig } from '../axios/types';
import type { AxiosCacheInstance, CacheRequestConfig } from '../cache/axios';
import type { AxiosInterceptor } from './types';
export declare class CacheRequestInterceptor implements AxiosInterceptor<CacheRequestConfig> {
export declare class CacheRequestInterceptor<D> implements AxiosInterceptor<CacheRequestConfig<D>> {
readonly axios: AxiosCacheInstance;
constructor(axios: AxiosCacheInstance);
use: () => void;
onFulfilled: (config: CacheRequestConfig) => Promise<CacheRequestConfig>;
onFulfilled: (config: CacheRequestConfig<D>) => Promise<CacheRequestConfig<D>>;
}
//# sourceMappingURL=request.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheRequestInterceptor = void 0;
const deferred_1 = require("../util/deferred");
const status_codes_1 = require("../util/status-codes");
const deferred_1 = require("typed-core/dist/promises/deferred");
class CacheRequestInterceptor {

@@ -44,3 +43,3 @@ axios;

*/
this.axios.waiting[key]?.catch(() => { });
this.axios.waiting[key]?.catch(() => undefined);
await this.axios.storage.set(key, {

@@ -52,3 +51,3 @@ state: 'loading',

}
let data = {};
let cachedResponse;
if (cache.state === 'loading') {

@@ -65,3 +64,3 @@ const deferred = this.axios.waiting[key];

try {
data = await deferred;
cachedResponse = await deferred;
}

@@ -74,10 +73,17 @@ catch (e) {

else {
data = cache.data;
cachedResponse = cache.data;
}
config.adapter = () => Promise.resolve({
config,
data: data.body,
headers: data.headers,
status: status_codes_1.CACHED_STATUS_CODE,
statusText: status_codes_1.CACHED_STATUS_TEXT
config.adapter = () =>
/**
* Even though the response interceptor receives this one from
* here, it has been configured to ignore cached responses: true
*/
Promise.resolve({
config: config,
data: cachedResponse.data,
headers: cachedResponse.headers,
status: cachedResponse.status,
statusText: cachedResponse.statusText,
cached: true,
id: key
});

@@ -84,0 +90,0 @@ return config;

@@ -1,4 +0,5 @@

import type { AxiosCacheInstance, CacheAxiosResponse } from '../axios/types';
import type { AxiosResponse } from 'axios';
import type { AxiosCacheInstance, CacheAxiosResponse } from '../cache/axios';
import type { AxiosInterceptor } from './types';
export declare class CacheResponseInterceptor<R> implements AxiosInterceptor<CacheAxiosResponse<R>> {
export declare class CacheResponseInterceptor<R, D> implements AxiosInterceptor<CacheAxiosResponse<R, D>> {
readonly axios: AxiosCacheInstance;

@@ -13,4 +14,4 @@ constructor(axios: AxiosCacheInstance);

private rejectResponse;
onFulfilled: (response: CacheAxiosResponse<R>) => Promise<CacheAxiosResponse<R>>;
onFulfilled: (axiosResponse: AxiosResponse<R, D>) => Promise<CacheAxiosResponse<R, D>>;
}
//# sourceMappingURL=response.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheResponseInterceptor = void 0;
const object_1 = require("typed-core/dist/core/object");
const cache_predicate_1 = require("../util/cache-predicate");

@@ -14,3 +15,3 @@ const update_cache_1 = require("../util/update-cache");

};
testCachePredicate = (response, { cache }) => {
testCachePredicate = (response, cache) => {
const cachePredicate = cache?.cachePredicate || this.axios.defaults.cache.cachePredicate;

@@ -32,11 +33,25 @@ return ((typeof cachePredicate === 'function' && cachePredicate(response)) ||

};
onFulfilled = async (response) => {
const key = this.axios.generateKey(response.config);
response.id = key;
onFulfilled = async (axiosResponse) => {
const key = this.axios.generateKey(axiosResponse.config);
const response = {
id: key,
// When the request interceptor override the request adapter, it means
// that the response.cached will be true and therefore, the request was cached.
cached: axiosResponse.cached || false,
...axiosResponse
};
// Skip cache
if (response.config.cache === false) {
return { ...response, cached: false };
}
// Response was marked as cached
if (response.cached) {
return response;
}
const cache = await this.axios.storage.get(key);
// Response shouldn't be cached or was already cached
/**
* From now on, the cache and response represents the state of the
* first response to a request, which has not yet been cached or
* processed before.
*/
if (cache.state !== 'loading') {

@@ -46,3 +61,3 @@ return response;

// Config told that this response should be cached.
if (!this.testCachePredicate(response, response.config)) {
if (!this.testCachePredicate(response, response.config.cache)) {
await this.rejectResponse(key);

@@ -62,10 +77,10 @@ return response;

const newCache = {
data: { body: response.data, headers: response.headers },
state: 'cached',
ttl: ttl,
createdAt: Date.now()
createdAt: Date.now(),
data: (0, object_1.extract)(response, ['data', 'headers', 'status', 'statusText'])
};
// Update other entries before updating himself
if (response.config.cache?.update) {
(0, update_cache_1.updateCache)(this.axios, response.data, response.config.cache.update);
(0, update_cache_1.updateCache)(this.axios.storage, response.data, response.config.cache.update);
}

@@ -76,3 +91,5 @@ const deferred = this.axios.waiting[key];

delete this.axios.waiting[key];
// Define this key as cache on the storage
await this.axios.storage.set(key, newCache);
// Return the response with cached as false, because it was not cached at all
return response;

@@ -79,0 +96,0 @@ };

@@ -5,3 +5,4 @@ export interface AxiosInterceptor<T> {

/**
* Should apply this interceptor to an already provided axios instance
* Should apply this interceptor to an already provided axios
* instance. Does not call this method explicitly.
*/

@@ -8,0 +9,0 @@ use(): void;

@@ -19,4 +19,6 @@ export interface CacheStorage {

export declare type CachedResponse = {
headers?: any;
body?: any;
data?: any;
headers: Record<string, string>;
status: number;
statusText: string;
};

@@ -23,0 +25,0 @@ /**

import type { AxiosResponse } from 'axios';
import type { CachePredicateObject } from './types';
export declare function checkPredicateObject<R>(response: AxiosResponse<R>, { statusCheck, containsHeaders: containsHeader, responseMatch }: CachePredicateObject): boolean;
export declare function checkPredicateObject<R>(response: AxiosResponse<R>, { statusCheck, containsHeaders, responseMatch }: CachePredicateObject): boolean;
//# sourceMappingURL=cache-predicate.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkPredicateObject = void 0;
function checkPredicateObject(response, { statusCheck, containsHeaders: containsHeader, responseMatch }) {
function checkPredicateObject(response, { statusCheck, containsHeaders, responseMatch }) {
if (statusCheck) {

@@ -19,6 +19,6 @@ if (typeof statusCheck === 'function') {

}
if (containsHeader) {
for (const headerName in containsHeader) {
if (containsHeaders) {
for (const headerName in containsHeaders) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const value = containsHeader[headerName];
const value = containsHeaders[headerName];
const header = response.headers[headerName];

@@ -25,0 +25,0 @@ // At any case, if the header is not found, the predicate fails.

import type { AxiosResponse } from 'axios';
import type { CacheRequestConfig } from '../axios/types';
import type { CacheRequestConfig } from '../cache/axios';
export declare type CachePredicate = CachePredicateObject | (<R>(response: AxiosResponse<R>) => boolean);

@@ -25,3 +25,3 @@ export declare type CachePredicateObject = {

*/
export declare type KeyGenerator = (options: CacheRequestConfig) => string;
export declare type KeyGenerator = <R>(options: CacheRequestConfig<R>) => string;
//# sourceMappingURL=types.d.ts.map

@@ -1,3 +0,4 @@

import type { AxiosCacheInstance, CacheUpdater } from '../axios/types';
export declare function updateCache(axios: AxiosCacheInstance, data: any, entries: Record<string, CacheUpdater>): Promise<void>;
import type { CachedStorageValue, CacheStorage, EmptyStorageValue } from '../storage/types';
export declare type CacheUpdater = 'delete' | ((cached: EmptyStorageValue | CachedStorageValue, newData: any) => CachedStorageValue | void);
export declare function updateCache<T = any>(storage: CacheStorage, data: T, entries: Record<string, CacheUpdater>): Promise<void>;
//# sourceMappingURL=update-cache.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateCache = void 0;
async function updateCache(axios, data, entries) {
async function updateCache(storage, data, entries) {
for (const cacheKey in entries) {

@@ -9,6 +9,6 @@ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion

if (value == 'delete') {
await axios.storage.remove(cacheKey);
await storage.remove(cacheKey);
continue;
}
const oldValue = await axios.storage.get(cacheKey);
const oldValue = await storage.get(cacheKey);
if (oldValue.state === 'loading') {

@@ -19,6 +19,6 @@ throw new Error('cannot update the cache while loading');

if (newValue === undefined) {
await axios.storage.remove(cacheKey);
await storage.remove(cacheKey);
continue;
}
await axios.storage.set(cacheKey, newValue);
await storage.set(cacheKey, newValue);
}

@@ -25,0 +25,0 @@ }

{
"name": "axios-cache-interceptor",
"version": "0.3.0",
"version": "0.4.0",
"description": "Cache interceptor for axios",

@@ -40,3 +40,4 @@ "main": "dist/index.js",

"dependencies": {
"@tusbar/cache-control": "^0.6.0"
"@tusbar/cache-control": "^0.6.0",
"typed-core": "^1.3.0"
},

@@ -50,3 +51,3 @@ "devDependencies": {

"auto-changelog": "^2.3.0",
"axios": "^0.22.0",
"axios": "^0.23.0",
"eslint": "^7.32.0",

@@ -63,4 +64,4 @@ "eslint-config-prettier": "^8.3.0",

"peerDependencies": {
"axios": "~0.22.0"
"axios": "~0.23.0"
}
}

@@ -66,18 +66,15 @@ <br />

import axios from 'axios';
import { createCache, SessionCacheStorage } from 'axios-cache-interceptor';
import { useCache, SessionCacheStorage } from 'axios-cache-interceptor';
// Any custom axios instance
const api = axios.create();
// Other axios instance with caching enabled
const cachedApi = createCache(api, {
// Store values on window.sessionStorage
storage: new SessionCacheStorage(),
// Use the max-age header to determine the cache expiration time
interpretHeader: true
// An axios instance with modified types
const api = useCache(axios.create(), {
/* options */
});
// Make a simple request, with caching support, to the api
const { data } = await cachedApi.get('https://api.example.com/');
const resp1 = await api.get('https://api.example.com/');
// resp1.cached = false
const resp2 = await api.get('https://api.example.com/');
// resp2.cached = true
```

@@ -97,15 +94,18 @@

- [Request id](#request-id)
- [Response object](#response-object)
- [response.cached](#responsecached)
- [response.id](#responseid)
- [Global configuration](#global-configuration)
- [storage](#storage)
- [generateKey](#generatekey)
- [waiting](#waiting)
- [headerInterpreter](#headerinterpreter)
- [requestInterceptor and responseInterceptor](#requestinterceptor-and-responseinterceptor)
- [config.storage](#configstorage)
- [config.generateKey](#configgeneratekey)
- [config.waiting](#configwaiting)
- [config.headerInterpreter](#configheaderinterpreter)
- [config.requestInterceptor and config.responseInterceptor](#configrequestinterceptor-and-configresponseinterceptor)
- [Per-request configuration](#per-request-configuration)
- [ttl](#ttl)
- [interpretHeader](#interpretheader)
- [methods](#methods)
- [cachePredicate](#cachepredicate)
- [update](#update)
- [Inspiration](#inspiration)
- [request.id](#requestid)
- [request.cache.ttl](#requestcachettl)
- [request.cache.interpretHeader](#requestcacheinterpretheader)
- [request.cache.methods](#requestcachemethods)
- [request.cache.cachePredicate](#requestcachecachepredicate)
- [request.cache.update](#requestcacheupdate)
- [License](#license)

@@ -133,2 +133,4 @@ - [Contact](#contact)

Below you can check what version of this package is supported by your version of axios.
But that does not mean that won't work with any version. Most of "breaking changes" made
by axios was it's types.

@@ -139,3 +141,4 @@ > **NOTE**: Below v0.3, axios was not configured as a peer dependency

| ----------------------------------------------------------------------------- | ------------------------------------------------ |
| `v0.3` | `>= v0.22` |
| `~v0.4` | `>= v0.32` |
| `~v0.3` | `>= v0.22` |
| `<= v0.2` | `v0.21` |

@@ -151,3 +154,3 @@

```js
import { applyCache } from 'axios-cache-interceptor';
import { useCache } from 'axios-cache-interceptor';

@@ -158,3 +161,3 @@ // Your axios instance

// Return the same axios instance, but with a modified Typescript type.
axios = applyCache(axios, {
axios = useCache(axios, {
/* options here */

@@ -180,3 +183,3 @@ });

- [x] Cache concurrent requests
- [x] Concurrent requests
- [x] Typescript support

@@ -201,10 +204,2 @@ - [x] Unit tests

The id is retrieved with the response object.
```js
const result = await cache.get(/* ... */);
const id = result.id; // <-- The id to find the cache and more;
```
Also, a custom id can be used to treat two requests as the same.

@@ -223,2 +218,26 @@

### Response object
Every response that came from our custom axios instance, will have some extras properties,
that you can retrieve like that:
```js
const result = await cache.get(/* ... */);
const id = result['propertyName'];
```
#### response.cached
A simple boolean to check whether this request was cached or not.
**NOTE**: The first response of a request capable of being cached will return
`cached: false`, as only your next requests will return `cached: true`.
#### response.id
The [request id](#request-id) resolved. This property represents the ID used throughout
the internal code. Remember that, depending on the
[config.keyGenerator](#configgeneratekey), it can be different as the provided on the
[request.id](#requestid).
<br />

@@ -236,3 +255,3 @@

### storage
### config.storage

@@ -257,3 +276,3 @@ The storage used to save the cache. Here will probably be the most changed property.

### generateKey
### config.generateKey

@@ -264,3 +283,3 @@ The function used to create different keys for each request. Defaults to a function that

### waiting
### config.waiting

@@ -272,3 +291,3 @@ A simple object that will hold a promise for each pending request. Used to handle

### headerInterpreter
### config.headerInterpreter

@@ -280,3 +299,3 @@ The function used to interpret all headers from a request and determine a time to live

### requestInterceptor and responseInterceptor
### config.requestInterceptor and config.responseInterceptor

@@ -296,4 +315,8 @@ The used request and response interceptor. Basically the core function of this library.

### ttl
### request.id
You can override the request id used by this property.
### request.cache.ttl
The time that the request will remain in cache. Some custom storage implementations may

@@ -304,3 +327,3 @@ not respect 100% the time.

### interpretHeader
### request.cache.interpretHeader

@@ -313,3 +336,3 @@ If activated, when the response is received, the `ttl` property will be inferred from the

### methods
### request.cache.methods

@@ -320,3 +343,3 @@ Specify what request methods should be cached.

### cachePredicate
### request.cache.cachePredicate

@@ -352,3 +375,3 @@ An object or function that will be tested against the response to test if it can be

### update
### request.cache.update

@@ -384,15 +407,2 @@ Once the request is resolved, this specifies what other responses should change their

## Inspiration
This project is highly inspired by several projects, written entirely in typescript,
supporting https headers and much more.
Take a look at some similar projects:
- [axios-cache-adapter](https://github.com/RasCarlito/axios-cache-adapter)
- [axios-cache-plugin](https://github.com/jin5354/axios-cache-plugin)
- [@tusbar/cache-control](https://github.com/tusbar/cache-control)
<br />
## License

@@ -399,0 +409,0 @@

@@ -1,7 +0,7 @@

export * from './axios/cache';
export * from './axios/types';
export * from './cache/axios';
export * from './cache/cache';
export * from './cache/create';
export * from './header/types';
export * from './interceptors/types';
export * from './storage/types';
export * as StatusCodes from './util/status-codes';
export * from './util/types';

@@ -1,3 +0,8 @@

import type { AxiosCacheInstance, CacheRequestConfig } from '../axios/types';
import { deferred } from 'typed-core/dist/promises/deferred';
import type {
AxiosCacheInstance,
CacheAxiosResponse,
CacheRequestConfig
} from '../cache/axios';
import type {
CachedResponse,

@@ -7,7 +12,7 @@ CachedStorageValue,

} from '../storage/types';
import { deferred } from '../util/deferred';
import { CACHED_STATUS_CODE, CACHED_STATUS_TEXT } from '../util/status-codes';
import type { AxiosInterceptor } from './types';
export class CacheRequestInterceptor implements AxiosInterceptor<CacheRequestConfig> {
export class CacheRequestInterceptor<D>
implements AxiosInterceptor<CacheRequestConfig<D>>
{
constructor(readonly axios: AxiosCacheInstance) {}

@@ -19,3 +24,3 @@

onFulfilled = async (config: CacheRequestConfig): Promise<CacheRequestConfig> => {
onFulfilled = async (config: CacheRequestConfig<D>): Promise<CacheRequestConfig<D>> => {
// Skip cache

@@ -61,3 +66,3 @@ if (config.cache === false) {

*/
this.axios.waiting[key]?.catch(() => {});
this.axios.waiting[key]?.catch(() => undefined);

@@ -72,3 +77,3 @@ await this.axios.storage.set(key, {

let data: CachedResponse = {};
let cachedResponse: CachedResponse;

@@ -88,3 +93,3 @@ if (cache.state === 'loading') {

try {
data = await deferred;
cachedResponse = await deferred;
} catch (e) {

@@ -95,12 +100,18 @@ // The deferred is rejected when the request that we are waiting rejected cache.

} else {
data = cache.data;
cachedResponse = cache.data;
}
config.adapter = () =>
Promise.resolve({
config,
data: data.body,
headers: data.headers,
status: CACHED_STATUS_CODE,
statusText: CACHED_STATUS_TEXT
/**
* Even though the response interceptor receives this one from
* here, it has been configured to ignore cached responses: true
*/
Promise.resolve<CacheAxiosResponse<unknown, D>>({
config: config,
data: cachedResponse.data,
headers: cachedResponse.headers,
status: cachedResponse.status,
statusText: cachedResponse.statusText,
cached: true,
id: key
});

@@ -107,0 +118,0 @@

import type { AxiosResponse } from 'axios';
import type {
AxiosCacheInstance,
CacheAxiosResponse,
CacheProperties,
CacheRequestConfig
} from '../axios/types';
import { extract } from 'typed-core/dist/core/object';
import type { AxiosCacheInstance, CacheAxiosResponse } from '../cache/axios';
import type { CacheProperties } from '../cache/cache';
import type { CachedStorageValue } from '../storage/types';

@@ -13,6 +10,4 @@ import { checkPredicateObject } from '../util/cache-predicate';

type CacheConfig = CacheRequestConfig & { cache?: Partial<CacheProperties> };
export class CacheResponseInterceptor<R>
implements AxiosInterceptor<CacheAxiosResponse<R>>
export class CacheResponseInterceptor<R, D>
implements AxiosInterceptor<CacheAxiosResponse<R, D>>
{

@@ -27,3 +22,3 @@ constructor(readonly axios: AxiosCacheInstance) {}

response: AxiosResponse<R>,
{ cache }: CacheConfig
cache?: Partial<CacheProperties>
): boolean => {

@@ -53,9 +48,21 @@ const cachePredicate =

onFulfilled = async (
response: CacheAxiosResponse<R>
): Promise<CacheAxiosResponse<R>> => {
const key = this.axios.generateKey(response.config);
response.id = key;
axiosResponse: AxiosResponse<R, D>
): Promise<CacheAxiosResponse<R, D>> => {
const key = this.axios.generateKey(axiosResponse.config);
const response: CacheAxiosResponse<R, D> = {
id: key,
// When the request interceptor override the request adapter, it means
// that the response.cached will be true and therefore, the request was cached.
cached: (axiosResponse as CacheAxiosResponse<R, D>).cached || false,
...axiosResponse
};
// Skip cache
if (response.config.cache === false) {
return { ...response, cached: false };
}
// Response was marked as cached
if (response.cached) {
return response;

@@ -66,3 +73,7 @@ }

// Response shouldn't be cached or was already cached
/**
* From now on, the cache and response represents the state of the
* first response to a request, which has not yet been cached or
* processed before.
*/
if (cache.state !== 'loading') {

@@ -73,3 +84,3 @@ return response;

// Config told that this response should be cached.
if (!this.testCachePredicate(response, response.config as CacheConfig)) {
if (!this.testCachePredicate(response, response.config.cache)) {
await this.rejectResponse(key);

@@ -94,6 +105,6 @@ return response;

const newCache: CachedStorageValue = {
data: { body: response.data, headers: response.headers },
state: 'cached',
ttl: ttl,
createdAt: Date.now()
createdAt: Date.now(),
data: extract(response, ['data', 'headers', 'status', 'statusText'])
};

@@ -103,3 +114,3 @@

if (response.config.cache?.update) {
updateCache(this.axios, response.data, response.config.cache.update);
updateCache(this.axios.storage, response.data, response.config.cache.update);
}

@@ -113,6 +124,8 @@

// Define this key as cache on the storage
await this.axios.storage.set(key, newCache);
// Return the response with cached as false, because it was not cached at all
return response;
};
}

@@ -6,5 +6,6 @@ export interface AxiosInterceptor<T> {

/**
* Should apply this interceptor to an already provided axios instance
* Should apply this interceptor to an already provided axios
* instance. Does not call this method explicitly.
*/
use(): void;
}

@@ -22,4 +22,6 @@ export interface CacheStorage {

export type CachedResponse = {
headers?: any;
body?: any;
data?: any;
headers: Record<string, string>;
status: number;
statusText: string;
};

@@ -26,0 +28,0 @@

@@ -6,3 +6,3 @@ import type { AxiosResponse } from 'axios';

response: AxiosResponse<R>,
{ statusCheck, containsHeaders: containsHeader, responseMatch }: CachePredicateObject
{ statusCheck, containsHeaders, responseMatch }: CachePredicateObject
): boolean {

@@ -25,6 +25,6 @@ if (statusCheck) {

if (containsHeader) {
for (const headerName in containsHeader) {
if (containsHeaders) {
for (const headerName in containsHeaders) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const value = containsHeader[headerName]!;
const value = containsHeaders[headerName]!;
const header = response.headers[headerName];

@@ -31,0 +31,0 @@

import type { AxiosResponse } from 'axios';
import type { CacheRequestConfig } from '../axios/types';
import type { CacheRequestConfig } from '../cache/axios';

@@ -32,2 +32,2 @@ export type CachePredicate =

*/
export type KeyGenerator = (options: CacheRequestConfig) => string;
export type KeyGenerator = <R>(options: CacheRequestConfig<R>) => string;

@@ -1,6 +0,17 @@

import type { AxiosCacheInstance, CacheUpdater } from '../axios/types';
import type {
CachedStorageValue,
CacheStorage,
EmptyStorageValue
} from '../storage/types';
export async function updateCache(
axios: AxiosCacheInstance,
data: any,
export type CacheUpdater =
| 'delete'
| ((
cached: EmptyStorageValue | CachedStorageValue,
newData: any
) => CachedStorageValue | void);
export async function updateCache<T = any>(
storage: CacheStorage,
data: T,
entries: Record<string, CacheUpdater>

@@ -13,7 +24,7 @@ ): Promise<void> {

if (value == 'delete') {
await axios.storage.remove(cacheKey);
await storage.remove(cacheKey);
continue;
}
const oldValue = await axios.storage.get(cacheKey);
const oldValue = await storage.get(cacheKey);

@@ -27,8 +38,8 @@ if (oldValue.state === 'loading') {

if (newValue === undefined) {
await axios.storage.remove(cacheKey);
await storage.remove(cacheKey);
continue;
}
await axios.storage.set(cacheKey, newValue);
await storage.set(cacheKey, newValue);
}
}

@@ -6,3 +6,3 @@ {

/* Projects */
"incremental": true /* Enable incremental compilation */,
"incremental": true /* Enable incremental compilation */,
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */

@@ -15,3 +15,3 @@ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */

/* Language and Environment */
"target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */

@@ -29,3 +29,3 @@ // "jsx": "preserve", /* Specify what JSX code is generated. */

/* Modules */
"module": "CommonJS" /* Specify what module code is generated. */,
"module": "CommonJS" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */

@@ -48,13 +48,13 @@ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */

/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
"declarationMap": true /* Create sourcemaps for d.ts files. */,
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
"declarationMap": true /* Create sourcemaps for d.ts files. */,
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
"sourceMap": true /* Create source map files for emitted JavaScript files. */,
"sourceMap": true /* Create source map files for emitted JavaScript files. */,
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
"importsNotUsedAsValues": "error" /* Specify emit/checking behavior for imports that are only used for types */,
"downlevelIteration": true /* Emit more compliant, but verbose and less performant JavaScript for iteration. */,
"importsNotUsedAsValues": "error" /* Specify emit/checking behavior for imports that are only used for types */,
"downlevelIteration": true /* Emit more compliant, but verbose and less performant JavaScript for iteration. */,
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */

@@ -65,3 +65,3 @@ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */

// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
"newLine": "lf" /* Set the newline character for emitting files. */,
"newLine": "lf" /* Set the newline character for emitting files. */,
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */

@@ -76,24 +76,24 @@ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */

// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
"strictNullChecks": true /* When type checking, take into account `null` and `undefined`. */,
"strictFunctionTypes": true /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */,
"strictBindCallApply": true /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */,
"strictPropertyInitialization": true /* Check for class properties that are declared but not set in the constructor. */,
"noImplicitThis": true /* Enable error reporting when `this` is given the type `any`. */,
"useUnknownInCatchVariables": true /* Type catch clause variables as 'unknown' instead of 'any'. */,
"alwaysStrict": true /* Ensure 'use strict' is always emitted. */,
"noUnusedLocals": true /* Enable error reporting when a local variables aren't read. */,
"noUnusedParameters": true /* Raise an error when a function parameter isn't read */,
"exactOptionalPropertyTypes": false /* Interpret optional property types as written, rather than adding 'undefined'. */,
"noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
"noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
"noUncheckedIndexedAccess": true /* Include 'undefined' in index signature results */,
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
"noPropertyAccessFromIndexSignature": false /* Enforces using indexed accessors for keys declared using an indexed type */,
"strictNullChecks": true /* When type checking, take into account `null` and `undefined`. */,
"strictFunctionTypes": true /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */,
"strictBindCallApply": true /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */,
"strictPropertyInitialization": true /* Check for class properties that are declared but not set in the constructor. */,
"noImplicitThis": true /* Enable error reporting when `this` is given the type `any`. */,
"useUnknownInCatchVariables": true /* Type catch clause variables as 'unknown' instead of 'any'. */,
"alwaysStrict": true /* Ensure 'use strict' is always emitted. */,
"noUnusedLocals": true /* Enable error reporting when a local variables aren't read. */,
"noUnusedParameters": true /* Raise an error when a function parameter isn't read */,
"exactOptionalPropertyTypes": false /* Interpret optional property types as written, rather than adding 'undefined'. */,
"noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
"noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
"noUncheckedIndexedAccess": true /* Include 'undefined' in index signature results */,
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
"noPropertyAccessFromIndexSignature": false /* Enforces using indexed accessors for keys declared using an indexed type */,
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */

@@ -104,4 +104,4 @@ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc