@hyper-fetch/core 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.json +7 -0
- package/README.md +83 -0
- package/dist/builder/builder.constants.d.ts +9 -0
- package/dist/builder/builder.d.ts +141 -0
- package/dist/builder/builder.types.d.ts +45 -0
- package/dist/builder/builder.utils.d.ts +10 -0
- package/dist/builder/index.d.ts +4 -0
- package/dist/cache/cache.d.ts +76 -0
- package/dist/cache/cache.events.d.ts +28 -0
- package/dist/cache/cache.types.d.ts +49 -0
- package/dist/cache/cache.utils.d.ts +6 -0
- package/dist/cache/index.d.ts +4 -0
- package/dist/client/fetch.client.bindings.d.ts +25 -0
- package/dist/client/fetch.client.constants.d.ts +1 -0
- package/dist/client/fetch.client.d.ts +2 -0
- package/dist/client/fetch.client.types.d.ts +57 -0
- package/dist/client/fetch.client.utils.d.ts +5 -0
- package/dist/client/index.d.ts +5 -0
- package/dist/command/command.d.ts +87 -0
- package/dist/command/command.types.d.ts +196 -0
- package/dist/command/command.utils.d.ts +22 -0
- package/dist/command/index.d.ts +3 -0
- package/dist/constants/http.constants.d.ts +7 -0
- package/dist/constants/time.constants.d.ts +11 -0
- package/dist/dispatcher/dispatcher.constants.d.ts +6 -0
- package/dist/dispatcher/dispatcher.d.ts +155 -0
- package/dist/dispatcher/dispatcher.events.d.ts +11 -0
- package/dist/dispatcher/dispatcher.types.d.ts +31 -0
- package/dist/dispatcher/dispatcher.utils.d.ts +10 -0
- package/dist/dispatcher/index.d.ts +5 -0
- package/dist/effect/fetch.effect.d.ts +14 -0
- package/dist/effect/fetch.effect.types.d.ts +32 -0
- package/dist/effect/index.d.ts +2 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +7 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.esm.js.map +7 -0
- package/dist/managers/app/app.manager.constants.d.ts +9 -0
- package/dist/managers/app/app.manager.d.ts +35 -0
- package/dist/managers/app/app.manager.events.d.ts +11 -0
- package/dist/managers/app/app.manager.types.d.ts +7 -0
- package/dist/managers/app/app.manager.utils.d.ts +4 -0
- package/dist/managers/app/index.d.ts +5 -0
- package/dist/managers/command/command.manager.d.ts +43 -0
- package/dist/managers/command/command.manager.events.d.ts +36 -0
- package/dist/managers/command/command.manager.types.d.ts +23 -0
- package/dist/managers/command/command.manager.utils.d.ts +16 -0
- package/dist/managers/command/index.d.ts +4 -0
- package/dist/managers/index.d.ts +3 -0
- package/dist/managers/logger/index.d.ts +4 -0
- package/dist/managers/logger/logger.manager.constants.d.ts +4 -0
- package/dist/managers/logger/logger.manager.d.ts +19 -0
- package/dist/managers/logger/logger.manager.types.d.ts +30 -0
- package/dist/managers/logger/logger.manager.utils.d.ts +3 -0
- package/dist/types/fetch.types.d.ts +15 -0
- package/dist/types/helpers.types.d.ts +11 -0
- package/dist/types/http.types.d.ts +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/uuid.utils.d.ts +1 -0
- package/package.json +60 -0
- package/src/builder/builder.constants.ts +9 -0
- package/src/builder/builder.ts +309 -0
- package/src/builder/builder.types.ts +57 -0
- package/src/builder/builder.utils.ts +178 -0
- package/src/builder/index.ts +4 -0
- package/src/cache/cache.events.ts +44 -0
- package/src/cache/cache.ts +221 -0
- package/src/cache/cache.types.ts +56 -0
- package/src/cache/cache.utils.ts +29 -0
- package/src/cache/index.ts +4 -0
- package/src/client/fetch.client.bindings.ts +290 -0
- package/src/client/fetch.client.constants.ts +3 -0
- package/src/client/fetch.client.ts +98 -0
- package/src/client/fetch.client.types.ts +83 -0
- package/src/client/fetch.client.utils.ts +28 -0
- package/src/client/index.ts +5 -0
- package/src/command/command.ts +539 -0
- package/src/command/command.types.ts +268 -0
- package/src/command/command.utils.ts +179 -0
- package/src/command/index.ts +3 -0
- package/src/constants/http.constants.ts +7 -0
- package/src/constants/time.constants.ts +11 -0
- package/src/dispatcher/dispatcher.constants.ts +6 -0
- package/src/dispatcher/dispatcher.events.ts +42 -0
- package/src/dispatcher/dispatcher.ts +596 -0
- package/src/dispatcher/dispatcher.types.ts +39 -0
- package/src/dispatcher/dispatcher.utils.ts +55 -0
- package/src/dispatcher/index.ts +5 -0
- package/src/effect/fetch.effect.ts +28 -0
- package/src/effect/fetch.effect.types.ts +35 -0
- package/src/effect/index.ts +2 -0
- package/src/index.ts +12 -0
- package/src/managers/app/app.manager.constants.ts +24 -0
- package/src/managers/app/app.manager.events.ts +34 -0
- package/src/managers/app/app.manager.ts +74 -0
- package/src/managers/app/app.manager.types.ts +8 -0
- package/src/managers/app/app.manager.utils.ts +34 -0
- package/src/managers/app/index.ts +5 -0
- package/src/managers/command/command.manager.events.ts +212 -0
- package/src/managers/command/command.manager.ts +68 -0
- package/src/managers/command/command.manager.types.ts +25 -0
- package/src/managers/command/command.manager.utils.ts +19 -0
- package/src/managers/command/index.ts +4 -0
- package/src/managers/index.ts +3 -0
- package/src/managers/logger/index.ts +4 -0
- package/src/managers/logger/logger.manager.constants.ts +24 -0
- package/src/managers/logger/logger.manager.ts +70 -0
- package/src/managers/logger/logger.manager.types.ts +35 -0
- package/src/managers/logger/logger.manager.utils.ts +27 -0
- package/src/types/fetch.types.ts +39 -0
- package/src/types/helpers.types.ts +15 -0
- package/src/types/http.types.ts +1 -0
- package/src/types/index.ts +3 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/uuid.utils.ts +3 -0
- package/tsconfig.json +8 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ClientQueryParam,
|
|
3
|
+
ClientQueryParamsType,
|
|
4
|
+
ClientQueryParamValues,
|
|
5
|
+
ClientResponseType,
|
|
6
|
+
QueryStringifyOptions,
|
|
7
|
+
} from "client";
|
|
8
|
+
import { CommandInstance } from "command";
|
|
9
|
+
import { stringifyDefaultOptions } from "builder";
|
|
10
|
+
import { NegativeTypes } from "types";
|
|
11
|
+
import { RequestInterceptorCallback, ResponseInterceptorCallback } from "./builder.types";
|
|
12
|
+
|
|
13
|
+
// Utils
|
|
14
|
+
|
|
15
|
+
export const stringifyValue = (response: string | unknown): string => {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.stringify(response as string);
|
|
18
|
+
} catch (err) {
|
|
19
|
+
return "";
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const interceptRequest = async (interceptors: RequestInterceptorCallback[], command: CommandInstance) => {
|
|
24
|
+
let newCommand = command;
|
|
25
|
+
if (!command.commandOptions.disableRequestInterceptors) {
|
|
26
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
27
|
+
for (const interceptor of interceptors) {
|
|
28
|
+
// eslint-disable-next-line no-await-in-loop
|
|
29
|
+
newCommand = (await interceptor(command)) as CommandInstance;
|
|
30
|
+
if (!newCommand) throw new Error("Request modifier must return command");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return newCommand;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const interceptResponse = async <GlobalErrorType>(
|
|
37
|
+
interceptors: ResponseInterceptorCallback[],
|
|
38
|
+
response: ClientResponseType<any, GlobalErrorType>,
|
|
39
|
+
command: CommandInstance,
|
|
40
|
+
) => {
|
|
41
|
+
let newResponse = response;
|
|
42
|
+
if (!command.commandOptions.disableResponseInterceptors) {
|
|
43
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
44
|
+
for (const interceptor of interceptors) {
|
|
45
|
+
// eslint-disable-next-line no-await-in-loop
|
|
46
|
+
newResponse = await interceptor(response, command);
|
|
47
|
+
if (!newResponse) throw new Error("Response modifier must return data");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return newResponse;
|
|
51
|
+
};
|
|
52
|
+
// Mappers
|
|
53
|
+
|
|
54
|
+
export const getClientHeaders = (command: CommandInstance) => {
|
|
55
|
+
const isFormData = command.data instanceof FormData;
|
|
56
|
+
const headers: HeadersInit = {};
|
|
57
|
+
|
|
58
|
+
if (!isFormData) headers["Content-Type"] = "application/json";
|
|
59
|
+
|
|
60
|
+
Object.assign(headers, command.headers);
|
|
61
|
+
return headers as HeadersInit;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const getClientPayload = (data: unknown): string | FormData => {
|
|
65
|
+
const isFormData = data instanceof FormData;
|
|
66
|
+
if (isFormData) return data;
|
|
67
|
+
|
|
68
|
+
return stringifyValue(data);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// Stringify
|
|
72
|
+
|
|
73
|
+
const isValidValue = (options: QueryStringifyOptions) => {
|
|
74
|
+
return (value: ClientQueryParam) => {
|
|
75
|
+
const { skipNull, skipEmptyString } = options;
|
|
76
|
+
|
|
77
|
+
if (skipEmptyString && value === undefined) {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
if (skipEmptyString && value === "") {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
if (skipNull && value === null) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return true;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const encodeValue = (value: string, { encode, strict }: Pick<QueryStringifyOptions, "encode" | "strict">): string => {
|
|
91
|
+
if (encode && strict) {
|
|
92
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
93
|
+
}
|
|
94
|
+
if (encode) {
|
|
95
|
+
return encodeURIComponent(value);
|
|
96
|
+
}
|
|
97
|
+
return value;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const encodeParams = (key: string, value: ClientQueryParam, options: QueryStringifyOptions) => {
|
|
101
|
+
const shouldSkip = !isValidValue(options)(value);
|
|
102
|
+
|
|
103
|
+
if (!key || shouldSkip) {
|
|
104
|
+
return "";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return `${encodeValue(key, options)}=${encodeValue(String(value), options)}`;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const encodeArray = (key: string, array: Array<ClientQueryParamValues>, options: QueryStringifyOptions): string => {
|
|
111
|
+
const { arrayFormat, arraySeparator } = options;
|
|
112
|
+
|
|
113
|
+
return array
|
|
114
|
+
.filter(isValidValue(options))
|
|
115
|
+
.reduce<string[]>((acc, value, index) => {
|
|
116
|
+
switch (arrayFormat) {
|
|
117
|
+
case "index": {
|
|
118
|
+
const keyValue = `${encodeValue(key, options)}[${encodeValue(String(index), options)}]=`;
|
|
119
|
+
acc.push(`${keyValue}${encodeValue(String(value), options)}`);
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
case "bracket": {
|
|
123
|
+
const keyValue = `${encodeValue(key, options)}[]=`;
|
|
124
|
+
acc.push(`${keyValue}${encodeValue(String(value), options)}`);
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
case "comma": {
|
|
128
|
+
const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || "";
|
|
129
|
+
return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(",")];
|
|
130
|
+
}
|
|
131
|
+
case "separator": {
|
|
132
|
+
const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || "";
|
|
133
|
+
return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
|
|
134
|
+
}
|
|
135
|
+
case "bracket-separator": {
|
|
136
|
+
const keyValue = (!acc.length && `${encodeValue(key, options)}[]=`) || "";
|
|
137
|
+
return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
|
|
138
|
+
}
|
|
139
|
+
default: {
|
|
140
|
+
const keyValue = `${encodeValue(key, options)}=`;
|
|
141
|
+
acc.push(`${keyValue}${encodeValue(String(value), options)}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return acc;
|
|
146
|
+
}, [])
|
|
147
|
+
.join("&");
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
export const stringifyQueryParams = (
|
|
151
|
+
queryParams: ClientQueryParamsType | string | NegativeTypes,
|
|
152
|
+
options: QueryStringifyOptions = stringifyDefaultOptions,
|
|
153
|
+
): string => {
|
|
154
|
+
if (!queryParams || !Object.keys(queryParams).length) {
|
|
155
|
+
return "";
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (typeof queryParams === "string") {
|
|
159
|
+
const hasQuestionMark = queryParams[0] === "?";
|
|
160
|
+
return hasQuestionMark ? queryParams : `?${queryParams}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const stringified = Object.entries(queryParams)
|
|
164
|
+
.map(([key, value]): string => {
|
|
165
|
+
if (Array.isArray(value)) {
|
|
166
|
+
return encodeArray(key, value, options);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return encodeParams(key, value, options);
|
|
170
|
+
})
|
|
171
|
+
.filter(Boolean)
|
|
172
|
+
.join("&");
|
|
173
|
+
|
|
174
|
+
if (stringified) {
|
|
175
|
+
return `?${stringified}`;
|
|
176
|
+
}
|
|
177
|
+
return "";
|
|
178
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import EventEmitter from "events";
|
|
2
|
+
|
|
3
|
+
import { CacheValueType, getRevalidateEventKey } from "cache";
|
|
4
|
+
import { getCacheKey } from "./cache.utils";
|
|
5
|
+
|
|
6
|
+
export const getCacheEvents = (emitter: EventEmitter) => ({
|
|
7
|
+
/**
|
|
8
|
+
* Set cache data
|
|
9
|
+
* @param cacheKey
|
|
10
|
+
* @param data
|
|
11
|
+
*/
|
|
12
|
+
emitCacheData: <Response, Error>(cacheKey: string, data: CacheValueType<Response, Error>): void => {
|
|
13
|
+
emitter.emit(getCacheKey(cacheKey), data);
|
|
14
|
+
},
|
|
15
|
+
/**
|
|
16
|
+
* Revalidate cache values event
|
|
17
|
+
*/
|
|
18
|
+
emitRevalidation: (cacheKey: string): void => {
|
|
19
|
+
emitter.emit(getRevalidateEventKey(cacheKey));
|
|
20
|
+
},
|
|
21
|
+
/**
|
|
22
|
+
* Cache data listener
|
|
23
|
+
* @param cacheKey
|
|
24
|
+
* @param callback
|
|
25
|
+
* @returns
|
|
26
|
+
*/
|
|
27
|
+
onData: <Response, Error>(
|
|
28
|
+
cacheKey: string,
|
|
29
|
+
callback: (data: CacheValueType<Response, Error>) => void,
|
|
30
|
+
): VoidFunction => {
|
|
31
|
+
emitter.on(getCacheKey(cacheKey), callback);
|
|
32
|
+
return () => emitter.removeListener(getCacheKey(cacheKey), callback);
|
|
33
|
+
},
|
|
34
|
+
/**
|
|
35
|
+
* Cache invalidation listener
|
|
36
|
+
* @param cacheKey
|
|
37
|
+
* @param callback
|
|
38
|
+
* @returns
|
|
39
|
+
*/
|
|
40
|
+
onRevalidate: (cacheKey: string, callback: () => void): VoidFunction => {
|
|
41
|
+
emitter.on(getRevalidateEventKey(cacheKey), callback);
|
|
42
|
+
return () => emitter.removeListener(getRevalidateEventKey(cacheKey), callback);
|
|
43
|
+
},
|
|
44
|
+
});
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import EventEmitter from "events";
|
|
2
|
+
|
|
3
|
+
import { ClientResponseType } from "client";
|
|
4
|
+
import { BuilderInstance } from "builder";
|
|
5
|
+
import { CommandResponseDetails, LoggerType } from "managers";
|
|
6
|
+
import {
|
|
7
|
+
CacheOptionsType,
|
|
8
|
+
CacheAsyncStorageType,
|
|
9
|
+
CacheStorageType,
|
|
10
|
+
getCacheData,
|
|
11
|
+
getCacheEvents,
|
|
12
|
+
CacheValueType,
|
|
13
|
+
} from "cache";
|
|
14
|
+
import { CommandDump, CommandInstance } from "command";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Cache class handles the data exchange with the dispatchers.
|
|
18
|
+
*
|
|
19
|
+
* @note
|
|
20
|
+
* Keys used to save the values are created dynamically on the Command class
|
|
21
|
+
*
|
|
22
|
+
*/
|
|
23
|
+
export class Cache {
|
|
24
|
+
public emitter = new EventEmitter();
|
|
25
|
+
public events: ReturnType<typeof getCacheEvents>;
|
|
26
|
+
|
|
27
|
+
public storage: CacheStorageType;
|
|
28
|
+
public lazyStorage?: CacheAsyncStorageType;
|
|
29
|
+
public clearKey: string;
|
|
30
|
+
public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();
|
|
31
|
+
private logger: LoggerType;
|
|
32
|
+
|
|
33
|
+
constructor(public builder: BuilderInstance, public options?: CacheOptionsType) {
|
|
34
|
+
this.storage = this.options?.storage || new Map<string, CacheValueType>();
|
|
35
|
+
this.events = getCacheEvents(this.emitter);
|
|
36
|
+
this.options?.onInitialization?.(this);
|
|
37
|
+
|
|
38
|
+
this.clearKey = this.options?.clearKey || "";
|
|
39
|
+
this.lazyStorage = this.options?.lazyStorage;
|
|
40
|
+
this.logger = this.builder.loggerManager.init("Cache");
|
|
41
|
+
|
|
42
|
+
this.getLazyKeys().then((keys) => {
|
|
43
|
+
keys.forEach(this.scheduleGarbageCollector);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// Going back from offline should re-trigger garbage collection
|
|
47
|
+
this.builder.appManager.events.onOnline(() => {
|
|
48
|
+
this.getLazyKeys().then((keys) => {
|
|
49
|
+
keys.forEach(this.scheduleGarbageCollector);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Set the cache data to the storage
|
|
56
|
+
* @param command
|
|
57
|
+
* @param response
|
|
58
|
+
* @param details
|
|
59
|
+
* @returns
|
|
60
|
+
*/
|
|
61
|
+
set = <Response, Error>(
|
|
62
|
+
command: CommandInstance | CommandDump<CommandInstance>,
|
|
63
|
+
response: ClientResponseType<Response, Error>,
|
|
64
|
+
details: CommandResponseDetails,
|
|
65
|
+
): void => {
|
|
66
|
+
this.logger.debug("Processing cache response", { command, response, details });
|
|
67
|
+
const { cacheKey, cache, cacheTime } = command;
|
|
68
|
+
const cachedData = this.storage.get<Response, Error>(cacheKey);
|
|
69
|
+
|
|
70
|
+
// Once refresh error occurs we don't want to override already valid data in our cache with the thrown error
|
|
71
|
+
// We need to check it against cache and return last valid data we have
|
|
72
|
+
const data = getCacheData(cachedData?.data, response);
|
|
73
|
+
|
|
74
|
+
const newCacheData: CacheValueType = { data, details, cacheTime, clearKey: this.clearKey };
|
|
75
|
+
|
|
76
|
+
this.events.emitCacheData<Response, Error>(cacheKey, newCacheData);
|
|
77
|
+
this.logger.debug("Emitting cache response", { command, response, details });
|
|
78
|
+
|
|
79
|
+
// If request should not use cache - just emit response data
|
|
80
|
+
if (!cache) {
|
|
81
|
+
return this.logger.debug("Prevented saving response to cache", { command, response, details });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Only success data is valid for the cache store
|
|
85
|
+
if (!details.isFailed) {
|
|
86
|
+
this.logger.debug("Saving response to cache storage", { command, response, details });
|
|
87
|
+
this.storage.set<Response, Error>(cacheKey, newCacheData);
|
|
88
|
+
this.lazyStorage?.set<Response, Error>(cacheKey, newCacheData);
|
|
89
|
+
this.options?.onChange?.(cacheKey, newCacheData);
|
|
90
|
+
this.scheduleGarbageCollector(cacheKey);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.
|
|
96
|
+
* @param cacheKey
|
|
97
|
+
* @returns
|
|
98
|
+
*/
|
|
99
|
+
get = <Response, Error>(cacheKey: string): CacheValueType<Response, Error> | undefined => {
|
|
100
|
+
this.getLazyResource<Response, Error>(cacheKey);
|
|
101
|
+
const cachedData = this.storage.get<Response, Error>(cacheKey);
|
|
102
|
+
return cachedData;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Get sync storage keys, lazyStorage keys will not be included
|
|
107
|
+
* @returns
|
|
108
|
+
*/
|
|
109
|
+
keys = (): string[] => {
|
|
110
|
+
const values = this.storage.keys();
|
|
111
|
+
|
|
112
|
+
return Array.from(values);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Delete record from storages and trigger revalidation
|
|
117
|
+
* @param cacheKey
|
|
118
|
+
*/
|
|
119
|
+
delete = (cacheKey: string): void => {
|
|
120
|
+
this.logger.debug("Deleting cache element", { cacheKey });
|
|
121
|
+
this.storage.delete(cacheKey);
|
|
122
|
+
this.options?.onDelete?.(cacheKey);
|
|
123
|
+
this.lazyStorage?.delete(cacheKey);
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Revalidate cache by cacheKey or partial matching with RegExp
|
|
128
|
+
* @param cacheKey
|
|
129
|
+
*/
|
|
130
|
+
revalidate = async (cacheKey: string | RegExp) => {
|
|
131
|
+
this.logger.debug("Revalidating cache element", { cacheKey });
|
|
132
|
+
const keys = await this.getLazyKeys();
|
|
133
|
+
|
|
134
|
+
if (typeof cacheKey === "string") {
|
|
135
|
+
this.events.emitRevalidation(cacheKey);
|
|
136
|
+
this.delete(cacheKey);
|
|
137
|
+
} else {
|
|
138
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
139
|
+
for (const entityKey of keys) {
|
|
140
|
+
if (cacheKey.test(entityKey)) {
|
|
141
|
+
this.events.emitRevalidation(entityKey);
|
|
142
|
+
this.delete(entityKey);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Used to receive data from lazy storage
|
|
150
|
+
* @param cacheKey
|
|
151
|
+
*/
|
|
152
|
+
getLazyResource = async <Response, Error>(cacheKey: string): Promise<CacheValueType<Response, Error> | undefined> => {
|
|
153
|
+
const data = await this.lazyStorage?.get<Response, Error>(cacheKey);
|
|
154
|
+
const syncData = this.storage.get<Response, Error>(cacheKey);
|
|
155
|
+
|
|
156
|
+
// No data in lazy storage
|
|
157
|
+
if (!this.lazyStorage || !data) return syncData;
|
|
158
|
+
|
|
159
|
+
const now = +new Date();
|
|
160
|
+
const isNewestData = syncData ? syncData.details.timestamp < data.details.timestamp : true;
|
|
161
|
+
const isStaleData = data.cacheTime <= now - data.details.timestamp;
|
|
162
|
+
const isValidData = data.clearKey === this.clearKey;
|
|
163
|
+
|
|
164
|
+
if (!isValidData) {
|
|
165
|
+
this.lazyStorage.delete(cacheKey);
|
|
166
|
+
}
|
|
167
|
+
if (isNewestData && !isStaleData && isValidData) {
|
|
168
|
+
this.storage.set<Response, Error>(cacheKey, data);
|
|
169
|
+
this.events.emitCacheData<Response, Error>(cacheKey, data);
|
|
170
|
+
return data;
|
|
171
|
+
}
|
|
172
|
+
return syncData;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Used to receive keys from sync storage and lazy storage
|
|
177
|
+
* @param cacheKey
|
|
178
|
+
*/
|
|
179
|
+
getLazyKeys = async () => {
|
|
180
|
+
const keys = await this.lazyStorage?.keys();
|
|
181
|
+
const asyncKeys = Array.from(keys || []);
|
|
182
|
+
const syncKeys = Array.from(this.storage.keys());
|
|
183
|
+
|
|
184
|
+
return [...new Set([...asyncKeys, ...syncKeys])];
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Schedule garbage collection for given key
|
|
189
|
+
* @param cacheKey
|
|
190
|
+
* @returns
|
|
191
|
+
*/
|
|
192
|
+
scheduleGarbageCollector = async (cacheKey: string) => {
|
|
193
|
+
// We need to make sure that all of the values will be removed, also that we have the proper data
|
|
194
|
+
const cacheData = await this.getLazyResource(cacheKey);
|
|
195
|
+
|
|
196
|
+
if (cacheData) {
|
|
197
|
+
const timeLeft = cacheData.cacheTime + cacheData.details.timestamp - +new Date();
|
|
198
|
+
if (timeLeft >= 0) {
|
|
199
|
+
clearTimeout(this.garbageCollectors.get(cacheKey));
|
|
200
|
+
this.garbageCollectors.set(
|
|
201
|
+
cacheKey,
|
|
202
|
+
setTimeout(() => {
|
|
203
|
+
if (this.builder.appManager.isOnline) {
|
|
204
|
+
this.logger.info("Garbage collecting cache element", { cacheKey });
|
|
205
|
+
this.delete(cacheKey);
|
|
206
|
+
}
|
|
207
|
+
}, timeLeft),
|
|
208
|
+
);
|
|
209
|
+
} else if (this.builder.appManager.isOnline) {
|
|
210
|
+
this.delete(cacheKey);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Clear cache storages
|
|
217
|
+
*/
|
|
218
|
+
clear = async (): Promise<void> => {
|
|
219
|
+
this.storage.clear();
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Cache } from "cache";
|
|
2
|
+
import { ClientResponseType } from "client";
|
|
3
|
+
import { CommandResponseDetails } from "managers";
|
|
4
|
+
|
|
5
|
+
export type CacheOptionsType = {
|
|
6
|
+
/**
|
|
7
|
+
* Assign your custom sync storage
|
|
8
|
+
*/
|
|
9
|
+
storage?: CacheStorageType;
|
|
10
|
+
/**
|
|
11
|
+
* Lazy loading from remote resources - possibly persistent
|
|
12
|
+
*/
|
|
13
|
+
lazyStorage?: CacheAsyncStorageType;
|
|
14
|
+
/**
|
|
15
|
+
* Key to clear lazy storage data
|
|
16
|
+
*/
|
|
17
|
+
clearKey?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Initialization callback
|
|
20
|
+
*/
|
|
21
|
+
onInitialization?: (cache: Cache) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Callback for every change in the storage
|
|
24
|
+
*/
|
|
25
|
+
onChange?: <Response = any, Error = any>(key: string, data: CacheValueType<Response, Error>) => void;
|
|
26
|
+
/**
|
|
27
|
+
* Callback for every delete in the storage
|
|
28
|
+
*/
|
|
29
|
+
onDelete?: (key: string) => void;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// Values
|
|
33
|
+
export type CacheValueType<Response = any, Error = any> = {
|
|
34
|
+
data: ClientResponseType<Response, Error>;
|
|
35
|
+
details: CommandResponseDetails;
|
|
36
|
+
cacheTime: number;
|
|
37
|
+
clearKey: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// Storage
|
|
41
|
+
export type CacheAsyncStorageType = {
|
|
42
|
+
set: <Response, Error>(key: string, data: CacheValueType<Response, Error>) => Promise<void>;
|
|
43
|
+
get: <Response, Error>(key: string) => Promise<CacheValueType<Response, Error> | undefined>;
|
|
44
|
+
keys: () => Promise<string[] | IterableIterator<string> | string[]>;
|
|
45
|
+
delete: (key: string) => Promise<void>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type CacheStorageType = {
|
|
49
|
+
set: <Response, Error>(key: string, data: CacheValueType<Response, Error>) => void;
|
|
50
|
+
get: <Response, Error>(key: string) => CacheValueType<Response, Error> | undefined;
|
|
51
|
+
keys: () => string[] | IterableIterator<string> | string[];
|
|
52
|
+
delete: (key: string) => void;
|
|
53
|
+
clear: () => void;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type CacheInitialData = Record<string, CacheValueType>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { CommandInstance } from "command";
|
|
2
|
+
import { isFailedRequest } from "dispatcher";
|
|
3
|
+
import { ExtractClientReturnType } from "types";
|
|
4
|
+
|
|
5
|
+
export const getCacheData = <T extends CommandInstance>(
|
|
6
|
+
previousResponse: ExtractClientReturnType<T> | undefined,
|
|
7
|
+
response: ExtractClientReturnType<T>,
|
|
8
|
+
): ExtractClientReturnType<T> => {
|
|
9
|
+
const isFailed = isFailedRequest(response);
|
|
10
|
+
|
|
11
|
+
const previousData = isFailed && previousResponse ? previousResponse[0] : null;
|
|
12
|
+
const data = response[0] || previousData;
|
|
13
|
+
const error = response[1];
|
|
14
|
+
const status = response[2];
|
|
15
|
+
|
|
16
|
+
return [data, error, status];
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const getRevalidateEventKey = (key: string): string => {
|
|
20
|
+
return `${key}_revalidate`;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const getCacheKey = (key: string): string => {
|
|
24
|
+
return `${key}_cache`;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const getCacheIdKey = (key: string): string => {
|
|
28
|
+
return `${key}_cache_by_id`;
|
|
29
|
+
};
|