@hyper-fetch/react 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 +82 -0
- package/dist/config-provider/config-provider.d.ts +13 -0
- package/dist/config-provider/config-provider.types.d.ts +17 -0
- package/dist/config-provider/index.d.ts +2 -0
- package/dist/helpers/index.d.ts +2 -0
- package/dist/helpers/use-command-events/index.d.ts +2 -0
- package/dist/helpers/use-command-events/use-command-events.hooks.d.ts +9 -0
- package/dist/helpers/use-command-events/use-command-events.types.d.ts +80 -0
- package/dist/helpers/use-tracked-state/index.d.ts +4 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.constants.d.ts +2 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts +11 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts +72 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +7 -0
- package/dist/hooks/use-app-manager/index.d.ts +2 -0
- package/dist/hooks/use-app-manager/use-app-manager.hooks.d.ts +3 -0
- package/dist/hooks/use-app-manager/use-app-manager.types.d.ts +18 -0
- package/dist/hooks/use-cache/index.d.ts +3 -0
- package/dist/hooks/use-cache/use-cache.constants.d.ts +5 -0
- package/dist/hooks/use-cache/use-cache.hooks.d.ts +3 -0
- package/dist/hooks/use-cache/use-cache.types.d.ts +35 -0
- package/dist/hooks/use-fetch/index.d.ts +4 -0
- package/dist/hooks/use-fetch/use-fetch.constants.d.ts +7 -0
- package/dist/hooks/use-fetch/use-fetch.hooks.d.ts +9 -0
- package/dist/hooks/use-fetch/use-fetch.types.d.ts +85 -0
- package/dist/hooks/use-fetch/use-fetch.utils.d.ts +1 -0
- package/dist/hooks/use-queue/index.d.ts +3 -0
- package/dist/hooks/use-queue/use-queue.constants.d.ts +3 -0
- package/dist/hooks/use-queue/use-queue.hooks.d.ts +9 -0
- package/dist/hooks/use-queue/use-queue.types.d.ts +48 -0
- package/dist/hooks/use-submit/index.d.ts +3 -0
- package/dist/hooks/use-submit/use-submit.constants.d.ts +7 -0
- package/dist/hooks/use-submit/use-submit.hooks.d.ts +9 -0
- package/dist/hooks/use-submit/use-submit.types.d.ts +101 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +7 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.esm.js.map +7 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/invalidation.types.d.ts +2 -0
- package/dist/utils/bounce.utils.d.ts +7 -0
- package/dist/utils/deep-equal.utils.d.ts +13 -0
- package/dist/utils/index.d.ts +2 -0
- package/package.json +74 -0
- package/src/config-provider/config-provider.tsx +30 -0
- package/src/config-provider/config-provider.types.ts +21 -0
- package/src/config-provider/index.ts +2 -0
- package/src/helpers/index.ts +2 -0
- package/src/helpers/use-command-events/index.ts +2 -0
- package/src/helpers/use-command-events/use-command-events.hooks.ts +283 -0
- package/src/helpers/use-command-events/use-command-events.types.ts +108 -0
- package/src/helpers/use-tracked-state/index.ts +4 -0
- package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +10 -0
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +227 -0
- package/src/helpers/use-tracked-state/use-tracked-state.types.ts +85 -0
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +82 -0
- package/src/hooks/use-app-manager/index.ts +2 -0
- package/src/hooks/use-app-manager/use-app-manager.hooks.ts +36 -0
- package/src/hooks/use-app-manager/use-app-manager.types.ts +18 -0
- package/src/hooks/use-cache/index.ts +3 -0
- package/src/hooks/use-cache/use-cache.constants.ts +5 -0
- package/src/hooks/use-cache/use-cache.hooks.ts +90 -0
- package/src/hooks/use-cache/use-cache.types.ts +45 -0
- package/src/hooks/use-fetch/index.ts +4 -0
- package/src/hooks/use-fetch/use-fetch.constants.ts +25 -0
- package/src/hooks/use-fetch/use-fetch.hooks.ts +265 -0
- package/src/hooks/use-fetch/use-fetch.types.ts +90 -0
- package/src/hooks/use-fetch/use-fetch.utils.ts +7 -0
- package/src/hooks/use-queue/index.ts +3 -0
- package/src/hooks/use-queue/use-queue.constants.ts +7 -0
- package/src/hooks/use-queue/use-queue.hooks.ts +112 -0
- package/src/hooks/use-queue/use-queue.types.ts +51 -0
- package/src/hooks/use-submit/index.ts +3 -0
- package/src/hooks/use-submit/use-submit.constants.ts +17 -0
- package/src/hooks/use-submit/use-submit.hooks.ts +219 -0
- package/src/hooks/use-submit/use-submit.types.ts +119 -0
- package/src/index.ts +8 -0
- package/src/types/index.ts +1 -0
- package/src/types/invalidation.types.ts +3 -0
- package/src/utils/bounce.utils.ts +9 -0
- package/src/utils/deep-equal.utils.ts +64 -0
- package/src/utils/index.ts +2 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { useRef } from "react";
|
|
2
|
+
import {
|
|
3
|
+
Command,
|
|
4
|
+
getCommandKey,
|
|
5
|
+
ExtractClientReturnType,
|
|
6
|
+
commandSendRequest,
|
|
7
|
+
CommandInstance,
|
|
8
|
+
ClientResponseType,
|
|
9
|
+
ExtractResponse,
|
|
10
|
+
ExtractError,
|
|
11
|
+
FetchType,
|
|
12
|
+
} from "@hyper-fetch/core";
|
|
13
|
+
import { useDidMount } from "@better-typed/react-lifecycle-hooks";
|
|
14
|
+
import { useDebounce, useThrottle } from "@better-typed/react-performance-hooks";
|
|
15
|
+
|
|
16
|
+
import { UseSubmitOptionsType, useSubmitDefaultOptions, UseSubmitReturnType } from "hooks/use-submit";
|
|
17
|
+
import { useTrackedState, useCommandEvents } from "helpers";
|
|
18
|
+
import { useConfigProvider } from "config-provider";
|
|
19
|
+
import { getBounceData } from "utils";
|
|
20
|
+
import { InvalidationKeyType } from "types";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* This hooks aims to mutate data on the server.
|
|
24
|
+
* @param command
|
|
25
|
+
* @param options
|
|
26
|
+
* @returns
|
|
27
|
+
*/
|
|
28
|
+
export const useSubmit = <Command extends CommandInstance>(
|
|
29
|
+
command: Command,
|
|
30
|
+
options: UseSubmitOptionsType<Command> = useSubmitDefaultOptions,
|
|
31
|
+
): UseSubmitReturnType<Command> => {
|
|
32
|
+
// Build the configuration options
|
|
33
|
+
const [globalConfig] = useConfigProvider();
|
|
34
|
+
const { disabled, dependencyTracking, initialData, bounce, bounceType, bounceTime, deepCompare } = {
|
|
35
|
+
...useSubmitDefaultOptions,
|
|
36
|
+
...globalConfig.useSubmitConfig,
|
|
37
|
+
...options,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Because of the dynamic cacheKey / queueKey signing within the command we need to store it's latest instance
|
|
42
|
+
* so the events got triggered properly and show the latest result without mixing it up
|
|
43
|
+
*/
|
|
44
|
+
const { builder } = command;
|
|
45
|
+
const { cache, submitDispatcher: dispatcher, loggerManager } = builder;
|
|
46
|
+
|
|
47
|
+
const logger = useRef(loggerManager.init("useSubmit")).current;
|
|
48
|
+
const requestDebounce = useDebounce(bounceTime);
|
|
49
|
+
const requestThrottle = useThrottle(bounceTime);
|
|
50
|
+
const bounceResolver = useRef<(value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => void>(
|
|
51
|
+
() => null,
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
|
|
55
|
+
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
|
|
59
|
+
*/
|
|
60
|
+
const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<Command>({
|
|
61
|
+
logger,
|
|
62
|
+
command,
|
|
63
|
+
dispatcher,
|
|
64
|
+
initialData,
|
|
65
|
+
deepCompare,
|
|
66
|
+
dependencyTracking,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Handles the data exchange with the core logic - responses, loading, downloading etc
|
|
71
|
+
*/
|
|
72
|
+
const [callbacks, listeners] = useCommandEvents({
|
|
73
|
+
logger,
|
|
74
|
+
actions,
|
|
75
|
+
command,
|
|
76
|
+
dispatcher,
|
|
77
|
+
setCacheData,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const { addDataListener, addLifecycleListeners } = listeners;
|
|
81
|
+
|
|
82
|
+
// ******************
|
|
83
|
+
// Submitting
|
|
84
|
+
// ******************
|
|
85
|
+
|
|
86
|
+
const handleSubmit = (...parameters: Parameters<Command["send"]>) => {
|
|
87
|
+
const submitOptions = parameters[0] as FetchType<Command> | undefined;
|
|
88
|
+
const commandClone = command.clone(submitOptions as any) as Command;
|
|
89
|
+
|
|
90
|
+
if (disabled) {
|
|
91
|
+
logger.warning(`Cannot submit request`, { disabled, submitOptions });
|
|
92
|
+
throw new Error("Cannot submit request. Option 'disabled' is enabled");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const triggerRequest = () => {
|
|
96
|
+
addDataListener(commandClone);
|
|
97
|
+
return commandSendRequest(commandClone, {
|
|
98
|
+
dispatcherType: "submit",
|
|
99
|
+
...submitOptions,
|
|
100
|
+
onSettle: (requestId, cmd) => {
|
|
101
|
+
addLifecycleListeners(commandClone, requestId);
|
|
102
|
+
submitOptions?.onSettle?.(requestId, cmd);
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
return new Promise<ExtractClientReturnType<Command>>((resolve) => {
|
|
108
|
+
const performSubmit = async () => {
|
|
109
|
+
logger.debug(`Submitting request`, { disabled, submitOptions });
|
|
110
|
+
if (bounce) {
|
|
111
|
+
const bouncedResolve = bounceResolver.current;
|
|
112
|
+
// We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.
|
|
113
|
+
// By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.
|
|
114
|
+
// This way we can close previous promise, making sure our logic will not stuck in memory.
|
|
115
|
+
bounceResolver.current = (value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => {
|
|
116
|
+
// Trigger previous awaiting calls to resolve together in bounced batches
|
|
117
|
+
bouncedResolve(value);
|
|
118
|
+
resolve(value);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
// Start bounce
|
|
122
|
+
bounceFunction(async () => {
|
|
123
|
+
// We will always resolve previous calls as we stack the callbacks together until bounce function trigger
|
|
124
|
+
const callback = bounceResolver.current;
|
|
125
|
+
// Clean bounce resolvers to start the new stack
|
|
126
|
+
bounceResolver.current = () => null;
|
|
127
|
+
|
|
128
|
+
const value = await triggerRequest();
|
|
129
|
+
callback(value);
|
|
130
|
+
});
|
|
131
|
+
} else {
|
|
132
|
+
const value = await triggerRequest();
|
|
133
|
+
resolve(value);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
performSubmit();
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
// ******************
|
|
142
|
+
// Revalidation
|
|
143
|
+
// ******************
|
|
144
|
+
|
|
145
|
+
const handleRevalidation = (invalidateKey: InvalidationKeyType) => {
|
|
146
|
+
if (invalidateKey && invalidateKey instanceof Command) {
|
|
147
|
+
cache.revalidate(getCommandKey(invalidateKey));
|
|
148
|
+
} else if (invalidateKey && !(invalidateKey instanceof Command)) {
|
|
149
|
+
cache.revalidate(invalidateKey);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const revalidate = (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => {
|
|
154
|
+
if (!invalidateKey) return;
|
|
155
|
+
|
|
156
|
+
if (invalidateKey && Array.isArray(invalidateKey)) {
|
|
157
|
+
invalidateKey.forEach(handleRevalidation);
|
|
158
|
+
} else if (invalidateKey && !Array.isArray(invalidateKey)) {
|
|
159
|
+
handleRevalidation(invalidateKey);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
// ******************
|
|
164
|
+
// Misc
|
|
165
|
+
// ******************
|
|
166
|
+
|
|
167
|
+
const handlers = {
|
|
168
|
+
onSubmitSuccess: callbacks.onSuccess,
|
|
169
|
+
onSubmitError: callbacks.onError,
|
|
170
|
+
onSubmitFinished: callbacks.onFinished,
|
|
171
|
+
onSubmitRequestStart: callbacks.onRequestStart,
|
|
172
|
+
onSubmitResponseStart: callbacks.onResponseStart,
|
|
173
|
+
onSubmitDownloadProgress: callbacks.onDownloadProgress,
|
|
174
|
+
onSubmitUploadProgress: callbacks.onUploadProgress,
|
|
175
|
+
onSubmitOfflineError: callbacks.onOfflineError,
|
|
176
|
+
onSubmitAbort: callbacks.onAbort,
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
// ******************
|
|
180
|
+
// Lifecycle
|
|
181
|
+
// ******************
|
|
182
|
+
|
|
183
|
+
useDidMount(() => {
|
|
184
|
+
addDataListener(command);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
submit: handleSubmit,
|
|
189
|
+
get data() {
|
|
190
|
+
setRenderKey("data");
|
|
191
|
+
return state.data;
|
|
192
|
+
},
|
|
193
|
+
get error() {
|
|
194
|
+
setRenderKey("error");
|
|
195
|
+
return state.error;
|
|
196
|
+
},
|
|
197
|
+
get submitting() {
|
|
198
|
+
setRenderKey("loading");
|
|
199
|
+
return state.loading;
|
|
200
|
+
},
|
|
201
|
+
get status() {
|
|
202
|
+
setRenderKey("status");
|
|
203
|
+
return state.status;
|
|
204
|
+
},
|
|
205
|
+
get retries() {
|
|
206
|
+
setRenderKey("retries");
|
|
207
|
+
return state.retries;
|
|
208
|
+
},
|
|
209
|
+
get timestamp() {
|
|
210
|
+
setRenderKey("timestamp");
|
|
211
|
+
return state.timestamp;
|
|
212
|
+
},
|
|
213
|
+
abort: callbacks.abort,
|
|
214
|
+
...actions,
|
|
215
|
+
...handlers,
|
|
216
|
+
bounce: getBounceData(bounceData),
|
|
217
|
+
revalidate,
|
|
218
|
+
};
|
|
219
|
+
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CacheValueType,
|
|
3
|
+
ExtractError,
|
|
4
|
+
ExtractResponse,
|
|
5
|
+
CommandInstance,
|
|
6
|
+
ExtractClientReturnType,
|
|
7
|
+
} from "@hyper-fetch/core";
|
|
8
|
+
|
|
9
|
+
import { isEqual } from "utils";
|
|
10
|
+
import {
|
|
11
|
+
OnErrorCallbackType,
|
|
12
|
+
OnFinishedCallbackType,
|
|
13
|
+
OnProgressCallbackType,
|
|
14
|
+
OnStartCallbackType,
|
|
15
|
+
OnSuccessCallbackType,
|
|
16
|
+
UseTrackedStateType,
|
|
17
|
+
UseTrackedStateActions,
|
|
18
|
+
} from "helpers";
|
|
19
|
+
import { InvalidationKeyType } from "types";
|
|
20
|
+
|
|
21
|
+
export type UseSubmitOptionsType<T extends CommandInstance> = {
|
|
22
|
+
/**
|
|
23
|
+
* Disable fetching
|
|
24
|
+
*/
|
|
25
|
+
disabled?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* If cache is empty we can use placeholder data.
|
|
28
|
+
*/
|
|
29
|
+
initialData?: CacheValueType<ExtractResponse<T>, ExtractError<T>>["data"] | null;
|
|
30
|
+
/**
|
|
31
|
+
* Enable/disable debouncing for often changing keys or refreshing, to limit requests to server.
|
|
32
|
+
*/
|
|
33
|
+
bounce?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Possibility to choose between debounce and throttle approaches
|
|
36
|
+
*/
|
|
37
|
+
bounceType?: "debounce" | "throttle";
|
|
38
|
+
/**
|
|
39
|
+
* How long it should bounce requests.
|
|
40
|
+
*/
|
|
41
|
+
bounceTime?: number;
|
|
42
|
+
/**
|
|
43
|
+
* If `true` it will rerender only when values used by our component gets changed. Otherwise it will rerender on any change.
|
|
44
|
+
*/
|
|
45
|
+
dependencyTracking?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Deep comparison function for hook to check for equality in incoming data, to limit rerenders.
|
|
48
|
+
*/
|
|
49
|
+
deepCompare?: boolean | typeof isEqual;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export type UseSubmitReturnType<T extends CommandInstance> = Omit<UseTrackedStateType<T>, "loading"> &
|
|
53
|
+
UseTrackedStateActions<T> & {
|
|
54
|
+
/**
|
|
55
|
+
* Callback which allows to cancel ongoing requests from given queueKey.
|
|
56
|
+
*/
|
|
57
|
+
abort: () => void;
|
|
58
|
+
/**
|
|
59
|
+
* Helper hook listening on success response.
|
|
60
|
+
*/
|
|
61
|
+
onSubmitSuccess: (callback: OnSuccessCallbackType<T>) => void;
|
|
62
|
+
/**
|
|
63
|
+
* Helper hook listening on error response.
|
|
64
|
+
*/
|
|
65
|
+
onSubmitError: (callback: OnErrorCallbackType<T>) => void;
|
|
66
|
+
/**
|
|
67
|
+
* Helper hook listening on any response.
|
|
68
|
+
*/
|
|
69
|
+
onSubmitFinished: (callback: OnFinishedCallbackType<T>) => void;
|
|
70
|
+
/**
|
|
71
|
+
* Helper hook listening on request start.
|
|
72
|
+
*/
|
|
73
|
+
onSubmitRequestStart: (callback: OnStartCallbackType<T>) => void;
|
|
74
|
+
/**
|
|
75
|
+
* Helper hook listening on response start(before we receive all data from server).
|
|
76
|
+
*/
|
|
77
|
+
onSubmitResponseStart: (callback: OnStartCallbackType<T>) => void;
|
|
78
|
+
/**
|
|
79
|
+
* Helper hook listening on download progress ETA. We can later match given requests by their id's or command instance which holds all data which is being transferred.
|
|
80
|
+
*/
|
|
81
|
+
onSubmitDownloadProgress: (callback: OnProgressCallbackType) => void;
|
|
82
|
+
/**
|
|
83
|
+
* Helper hook listening on upload progress ETA. We can later match given requests by their id's or command instance which holds all data which is being transferred.
|
|
84
|
+
*/
|
|
85
|
+
onSubmitUploadProgress: (callback: OnProgressCallbackType) => void;
|
|
86
|
+
/**
|
|
87
|
+
* Helper hook listening on aborting of requests. Abort events are not triggering onError callbacks.
|
|
88
|
+
*/
|
|
89
|
+
onSubmitAbort: (callback: OnErrorCallbackType<T>) => void;
|
|
90
|
+
/**
|
|
91
|
+
* Helper hook listening on request going into offline awaiting for network connection to be restored. It will not trigger onError when 'offline' mode is set on command.
|
|
92
|
+
*/
|
|
93
|
+
onSubmitOfflineError: (callback: OnErrorCallbackType<T>) => void;
|
|
94
|
+
/**
|
|
95
|
+
* Method responsible for triggering requests. It return Promise which will be resolved with the request.
|
|
96
|
+
*/
|
|
97
|
+
submit: (...parameters: Parameters<T["send"]>) => Promise<ExtractClientReturnType<T>>;
|
|
98
|
+
/**
|
|
99
|
+
* Request loading state
|
|
100
|
+
*/
|
|
101
|
+
submitting: boolean;
|
|
102
|
+
/**
|
|
103
|
+
* Data related to current state of the bounce usage
|
|
104
|
+
*/
|
|
105
|
+
bounce: {
|
|
106
|
+
/**
|
|
107
|
+
* Active state of the bounce method
|
|
108
|
+
*/
|
|
109
|
+
active: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Method to stop the active bounce method execution
|
|
112
|
+
*/
|
|
113
|
+
reset: () => void;
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* Revalidate current command resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
|
|
117
|
+
*/
|
|
118
|
+
revalidate: (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => void;
|
|
119
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from "./hooks/use-fetch";
|
|
2
|
+
export * from "./hooks/use-submit";
|
|
3
|
+
export * from "./hooks/use-queue";
|
|
4
|
+
export * from "./hooks/use-cache";
|
|
5
|
+
export * from "./hooks/use-app-manager";
|
|
6
|
+
export * from "./helpers";
|
|
7
|
+
export * from "./types";
|
|
8
|
+
export * from "./utils";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./invalidation.types";
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Check if value is empty
|
|
3
|
+
* @param value any object or primitive
|
|
4
|
+
* @returns true when value is empty
|
|
5
|
+
*/
|
|
6
|
+
export const isEmpty = (value: unknown): boolean => {
|
|
7
|
+
const valueType = Object.prototype.toString.call(value);
|
|
8
|
+
if (Array.isArray(value)) return !value.length;
|
|
9
|
+
if (typeof value === "object" && value !== null && valueType === "[object Object]") return !Object.keys(value).length;
|
|
10
|
+
return false;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Allow to deep compare any passed values
|
|
15
|
+
* @param firstValue unknown
|
|
16
|
+
* @param secondValue unknown
|
|
17
|
+
* @returns true when elements are equal
|
|
18
|
+
*/
|
|
19
|
+
export const isEqual = (firstValue: unknown, secondValue: unknown): boolean => {
|
|
20
|
+
const firstValueType = Object.prototype.toString.call(firstValue);
|
|
21
|
+
const secondValueType = Object.prototype.toString.call(secondValue);
|
|
22
|
+
|
|
23
|
+
const firstType = typeof firstValue;
|
|
24
|
+
const secondType = typeof secondValue;
|
|
25
|
+
|
|
26
|
+
const isType = (type: unknown) => firstType === type && secondType === type;
|
|
27
|
+
const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;
|
|
28
|
+
|
|
29
|
+
// Compared types are different
|
|
30
|
+
if (firstValueType !== secondValueType) return false;
|
|
31
|
+
|
|
32
|
+
// Null
|
|
33
|
+
if (firstValue === null && secondValue === null) return true;
|
|
34
|
+
|
|
35
|
+
// NaN
|
|
36
|
+
if (isType("number") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) return true;
|
|
37
|
+
|
|
38
|
+
// Empty Array or Object
|
|
39
|
+
if (isEmpty(firstValue) && isEmpty(secondValue)) return true;
|
|
40
|
+
|
|
41
|
+
// Array
|
|
42
|
+
if (Array.isArray(firstValue) && Array.isArray(secondValue)) {
|
|
43
|
+
if (firstValue.length !== secondValue.length) return false;
|
|
44
|
+
|
|
45
|
+
return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Object
|
|
49
|
+
if (isType("object") && isTypeValue("[object Object]")) {
|
|
50
|
+
if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) return false;
|
|
51
|
+
|
|
52
|
+
return !Object.entries(firstValue as object).some(
|
|
53
|
+
([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Date
|
|
58
|
+
if (firstValue instanceof Date && secondValue instanceof Date) {
|
|
59
|
+
return +firstValue === +secondValue;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// undefined, string, number, bool
|
|
63
|
+
return firstValue === secondValue;
|
|
64
|
+
};
|