react-redux-cache 0.19.3 → 0.19.4
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/README.md +1 -1
- package/dist/cjs/createActions.js +65 -0
- package/dist/cjs/createCache.js +208 -0
- package/dist/cjs/createCacheReducer.js +285 -0
- package/dist/cjs/createSelectors.js +68 -0
- package/dist/cjs/index.js +83 -0
- package/dist/cjs/mutate.js +161 -0
- package/dist/cjs/query.js +180 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/useMutation.js +82 -0
- package/dist/cjs/useQuery.js +121 -0
- package/dist/cjs/utilsAndConstants.js +189 -0
- package/dist/esm/createActions.js +61 -0
- package/dist/esm/createCache.js +203 -0
- package/dist/esm/createCacheReducer.js +271 -0
- package/dist/esm/createSelectors.js +64 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/mutate.js +157 -0
- package/dist/esm/query.js +169 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/useMutation.js +88 -0
- package/dist/esm/useQuery.js +125 -0
- package/dist/esm/utilsAndConstants.js +168 -0
- package/dist/types/createActions.d.ts +106 -0
- package/dist/types/createCache.d.ts +712 -0
- package/dist/types/createCacheReducer.d.ts +11 -0
- package/dist/types/createSelectors.d.ts +79 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/mutate.d.ts +94 -0
- package/dist/types/query.d.ts +122 -0
- package/dist/types/types.d.ts +322 -0
- package/dist/types/useMutation.d.ts +39 -0
- package/dist/types/useQuery.d.ts +40 -0
- package/dist/types/utilsAndConstants.d.ts +39 -0
- package/package.json +21 -10
- package/dist/createActions.d.ts +0 -83
- package/dist/createActions.js +0 -64
- package/dist/createCache.d.ts +0 -378
- package/dist/createCache.js +0 -192
- package/dist/createCacheReducer.d.ts +0 -3
- package/dist/createCacheReducer.js +0 -243
- package/dist/createSelectors.d.ts +0 -18
- package/dist/createSelectors.js +0 -61
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -53
- package/dist/mutate.d.ts +0 -4
- package/dist/mutate.js +0 -98
- package/dist/query.d.ts +0 -4
- package/dist/query.js +0 -107
- package/dist/types.d.ts +0 -187
- package/dist/types.js +0 -3
- package/dist/useMutation.d.ts +0 -4
- package/dist/useMutation.js +0 -61
- package/dist/useQuery.d.ts +0 -4
- package/dist/useQuery.js +0 -77
- package/dist/utilsAndConstants.d.ts +0 -20
- package/dist/utilsAndConstants.js +0 -161
package/dist/types.d.ts
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import type { Actions } from './createActions';
|
|
2
|
-
import type { Selectors } from './createSelectors';
|
|
3
|
-
export type Key = string | number | symbol;
|
|
4
|
-
export type Dict<T> = Record<Key, T>;
|
|
5
|
-
export type OptionalPartial<T, K extends keyof T> = Partial<{
|
|
6
|
-
[A in K]: Partial<T[A]>;
|
|
7
|
-
}> & Omit<T, K>;
|
|
8
|
-
/** Entity changes to be merged to the state. */
|
|
9
|
-
export type EntityChanges<T extends Typenames> = {
|
|
10
|
-
/** Entities that will be merged with existing. */
|
|
11
|
-
merge?: PartialEntitiesMap<T>;
|
|
12
|
-
/** Entities that will replace existing. */
|
|
13
|
-
replace?: Partial<EntitiesMap<T>>;
|
|
14
|
-
/** Ids of entities that will be removed. */
|
|
15
|
-
remove?: EntityIds<T>;
|
|
16
|
-
/** Alias for `merge` to support normalizr. */
|
|
17
|
-
entities?: EntityChanges<T>['merge'];
|
|
18
|
-
};
|
|
19
|
-
export type Store<S = unknown> = {
|
|
20
|
-
dispatch: (action: ReturnType<Actions[keyof Actions]>) => unknown;
|
|
21
|
-
getState: () => S;
|
|
22
|
-
};
|
|
23
|
-
/** Record of typename and its corresponding entity type */
|
|
24
|
-
export type Typenames = Record<string, object>;
|
|
25
|
-
export type Cache<N extends string, T extends Typenames, QP, QR, MP, MR> = {
|
|
26
|
-
/** Used as prefix for actions and in default cacheStateSelector for selecting cache state from store root state. */
|
|
27
|
-
name: N;
|
|
28
|
-
/** Cache options. */
|
|
29
|
-
options: CacheOptions;
|
|
30
|
-
/** Default options for queries and mutations. */
|
|
31
|
-
globals: Globals<N, T, QP, QR, MP, MR>;
|
|
32
|
-
/** Hooks to access and subscribe to the store. Imported from react-redux if not overridden. */
|
|
33
|
-
storeHooks: {
|
|
34
|
-
useStore: () => Store;
|
|
35
|
-
useSelector: <R>(selector: (state: unknown) => R, comparer?: (x: R, y: R) => boolean) => R;
|
|
36
|
-
};
|
|
37
|
-
/** Should return cache state from store root state. Default implementation returns `state[name]`. */
|
|
38
|
-
cacheStateSelector: (state: any) => CacheState<T, QP, QR, MP, MR>;
|
|
39
|
-
/** Queries. */
|
|
40
|
-
queries: {
|
|
41
|
-
[QK in keyof (QP & QR)]: QK extends keyof (QP | QR) ? QueryInfo<N, T, QP[QK], QR[QK], QP, QR, MP, MR> : never;
|
|
42
|
-
};
|
|
43
|
-
/** Mutations. */
|
|
44
|
-
mutations: {
|
|
45
|
-
[MK in keyof (MP & MR)]: MK extends keyof (MP | MR) ? MutationInfo<N, T, MP[MK], MR[MK], QP, QR, MP, MR> : never;
|
|
46
|
-
};
|
|
47
|
-
};
|
|
48
|
-
export type QueryStateComparer<T extends Typenames, P, R> = (x: QueryState<T, P, R> | undefined, y: QueryState<T, P, R> | undefined) => boolean;
|
|
49
|
-
export type Globals<N extends string, T extends Typenames, QP, QR, MP, MR> = {
|
|
50
|
-
/** Handles errors, not handled by onError from queries and mutations. @Default undefined. */
|
|
51
|
-
onError?: (error: unknown, key: string, params: unknown, store: Store, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>) => void;
|
|
52
|
-
/** Query options. */
|
|
53
|
-
queries: {
|
|
54
|
-
/** Determines when useQuery fetch triggers should start fetching. Fetch is performed if function returns true.
|
|
55
|
-
* Fetch triggers are: 1) mount 2) cache key change 3) skipFetch value change to false.
|
|
56
|
-
* @Default FetchPolicy.NoCacheOrExpired */
|
|
57
|
-
fetchPolicy: (expired: boolean, params: unknown, state: QueryState<T, unknown, unknown>, store: Store, selectors: Selectors<N, T, QP, QR, MP, MR>) => boolean;
|
|
58
|
-
/** Disables any fetches when set to true. Triggers fetch when changed to false. @Default false */
|
|
59
|
-
skipFetch: boolean;
|
|
60
|
-
/** If set, this value updates expiresAt value of query state when query result is received. @Default undefined */
|
|
61
|
-
secondsToLive?: number;
|
|
62
|
-
/** Either comparer function, or array of keys to subscribe by useQuery's useSelector. @Default compares result, loading, params, error. */
|
|
63
|
-
selectorComparer?: QueryStateComparer<T, unknown, unknown> | (keyof QueryState<T, unknown, unknown>)[];
|
|
64
|
-
};
|
|
65
|
-
};
|
|
66
|
-
export type CacheOptions = {
|
|
67
|
-
/** Enables additional validation with logging to console.warn. Recommened to enable in dev/testing mode. @Default true in dev mode. */
|
|
68
|
-
additionalValidation: boolean;
|
|
69
|
-
/** Enables debug logs. @Default false */
|
|
70
|
-
logsEnabled: boolean;
|
|
71
|
-
/**
|
|
72
|
-
* Enables deep comparison before merging entities to the state.
|
|
73
|
-
* Re-rendering is a heavier operation than comparison, so disabling it can lead to performance drop.
|
|
74
|
-
* Makes sense to disable only if merging equal results & entities to the state is a rare case.
|
|
75
|
-
* @Default true
|
|
76
|
-
*/
|
|
77
|
-
deepComparisonEnabled: boolean;
|
|
78
|
-
};
|
|
79
|
-
export type PartialEntitiesMap<T extends Typenames> = {
|
|
80
|
-
[K in keyof T]?: Dict<Partial<T[K]>>;
|
|
81
|
-
};
|
|
82
|
-
export type EntitiesMap<T extends Typenames> = {
|
|
83
|
-
[K in keyof T]?: Dict<T[K]>;
|
|
84
|
-
};
|
|
85
|
-
export type EntityIds<T extends Typenames> = {
|
|
86
|
-
[K in keyof T]?: Key[];
|
|
87
|
-
};
|
|
88
|
-
export type CacheState<T extends Typenames, QP, QR, MP, MR> = {
|
|
89
|
-
entities: EntitiesMap<T>;
|
|
90
|
-
queries: {
|
|
91
|
-
[QK in keyof (QP | QR)]: Dict<QueryState<T, QP[QK], QR[QK]> | undefined>;
|
|
92
|
-
};
|
|
93
|
-
mutations: {
|
|
94
|
-
[MK in keyof (MP | MR)]: MutationState<T, MP[MK], MR[MK]>;
|
|
95
|
-
};
|
|
96
|
-
};
|
|
97
|
-
export type QueryInfo<N extends string, T extends Typenames = Typenames, P = unknown, R = unknown, QP = unknown, QR = unknown, MP = unknown, MR = unknown> = Partial<Pick<Globals<N, T, QP, QR, MP, MR>['queries'], 'skipFetch' | 'secondsToLive'>> & {
|
|
98
|
-
query: NormalizedQuery<T, P, R>;
|
|
99
|
-
/** Determines when useQuery fetch triggers should start fetching. Fetch is performed if function returns true.
|
|
100
|
-
* Fetch triggers are: 1) mount 2) cache key change 3) skipFetch value change to false.
|
|
101
|
-
* @Default FetchPolicy.NoCacheOrExpired */
|
|
102
|
-
fetchPolicy?: (expired: boolean, params: P, queryState: QueryState<T, P, R>, store: Store, selectors: Selectors<N, T, QP, QR, MP, MR>) => boolean;
|
|
103
|
-
/** Merges results before saving to the store. Default implementation is using the latest result. */
|
|
104
|
-
mergeResults?: (oldResult: R | undefined, response: NormalizedQueryResponse<T, R>, params: P | undefined, store: Store, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>) => R;
|
|
105
|
-
/**
|
|
106
|
-
* Cache key is used for storing the query state and for performing a fetch when it changes. Queries with the same cache key share their state.
|
|
107
|
-
* Default implementation uses `String()` or `JSON.stringify` depending on type.
|
|
108
|
-
* It is recommended to override it when default implementation is not optimal or when keys in params object can be sorted in random order etc.
|
|
109
|
-
*/
|
|
110
|
-
getCacheKey?: (params?: P) => Key;
|
|
111
|
-
/** Called after fetch completed either successfully or not. */
|
|
112
|
-
onCompleted?: (response: NormalizedQueryResponse<T, R> | undefined, error: unknown | undefined, params: P | undefined, store: Store, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>) => void;
|
|
113
|
-
/** Called after fetch finished successfully. */
|
|
114
|
-
onSuccess?: (response: NormalizedQueryResponse<T, R>, params: P | undefined, store: Store, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>) => void;
|
|
115
|
-
/** Called after fetch finished with error. Should return true if error was handled and does not require global onError handling. */
|
|
116
|
-
onError?: (error: unknown, params: P | undefined, store: Store, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>) => boolean | void | null | undefined;
|
|
117
|
-
/** Either comparer function, or array of keys to subscribe by useQuery's useSelector. Default compares params, result, loading, error. */
|
|
118
|
-
selectorComparer?: QueryStateComparer<T, P, R> | (keyof QueryState<T, P, R>)[];
|
|
119
|
-
};
|
|
120
|
-
export type Query<P = unknown, R = unknown> = (
|
|
121
|
-
/** Query parameters */
|
|
122
|
-
params: P,
|
|
123
|
-
/** Store */
|
|
124
|
-
store: Store) => Promise<QueryResponse<R>>;
|
|
125
|
-
export type NormalizedQuery<T extends Typenames = Typenames, P = unknown, R = unknown> = (...args: Parameters<Query<P, R>>) => Promise<NormalizedQueryResponse<T, R>>;
|
|
126
|
-
export type QueryState<T extends Typenames, P, R> = MutationState<T, P, R> & {
|
|
127
|
-
/**
|
|
128
|
-
* Timestamp in milliseconds, after which state is considered expired.
|
|
129
|
-
* Hooks may refetch the query again when component mounts, cache key or skip option change, depending on the fetch policy.
|
|
130
|
-
* Client query calls also start making fetch if onlyIfExpired argument is truthy.
|
|
131
|
-
* */
|
|
132
|
-
expiresAt?: number;
|
|
133
|
-
};
|
|
134
|
-
export type UseQueryOptions<N extends string, T extends Typenames, QK extends keyof (QP & QR), QP, QR, MP, MR> = {
|
|
135
|
-
query: QK;
|
|
136
|
-
params: QK extends keyof (QP | QR) ? QP[QK] : never;
|
|
137
|
-
} & Pick<QueryInfo<N, T, QK extends keyof (QP | QR) ? QP[QK] : never, QK extends keyof (QP | QR) ? QR[QK] : never, QP, QR, MP, MR>, 'fetchPolicy' | 'skipFetch' | 'secondsToLive' | 'selectorComparer' | 'mergeResults' | 'onCompleted' | 'onSuccess' | 'onError'>;
|
|
138
|
-
export type QueryOptions<N extends string, T extends Typenames, QP, QR, QK extends keyof (QP & QR), MP, MR> = Omit<UseQueryOptions<N, T, QK, QP, QR, MP, MR>, 'skipFetch'> & {
|
|
139
|
-
/** If set to true, query will run only if it is expired or result not yet cached. */
|
|
140
|
-
onlyIfExpired?: boolean;
|
|
141
|
-
};
|
|
142
|
-
export type QueryResponse<R = unknown> = {
|
|
143
|
-
result: R;
|
|
144
|
-
/** If defined, overrides this value for query state, ignoring `secondsToLive`. */
|
|
145
|
-
expiresAt?: number;
|
|
146
|
-
};
|
|
147
|
-
export type NormalizedQueryResponse<T extends Typenames = Typenames, R = unknown> = EntityChanges<T> & QueryResponse<R>;
|
|
148
|
-
export type QueryResult<R = unknown> = {
|
|
149
|
-
error?: unknown;
|
|
150
|
-
/** Fetch cancelled reason. */
|
|
151
|
-
cancelled?: 'loading' | 'not-expired';
|
|
152
|
-
result?: R;
|
|
153
|
-
};
|
|
154
|
-
export type MutationInfo<N extends string, T extends Typenames = Typenames, P = unknown, R = unknown, QP = unknown, QR = unknown, MP = unknown, MR = unknown> = Pick<QueryInfo<N, T, P, R, QP, QR, MP, MR>, 'onCompleted' | 'onSuccess' | 'onError'> & {
|
|
155
|
-
mutation: NormalizedMutation<T, P, R>;
|
|
156
|
-
};
|
|
157
|
-
export type Mutation<P = unknown, R = unknown> = (
|
|
158
|
-
/** Mutation parameters */
|
|
159
|
-
params: P,
|
|
160
|
-
/** Store */
|
|
161
|
-
store: Store,
|
|
162
|
-
/** Signal is aborted for current mutation when the same mutation was called once again. */
|
|
163
|
-
abortSignal: AbortSignal) => Promise<MutationResponse<R>>;
|
|
164
|
-
export type NormalizedMutation<T extends Typenames = Typenames, P = unknown, R = unknown> = (...args: Parameters<Mutation<P, R>>) => Promise<NormalizedMutationResponse<T, R>>;
|
|
165
|
-
export type MutateOptions<N extends string, T extends Typenames, QP, QR, MP, MR, MK extends keyof (MP & MR)> = Pick<MutationInfo<N, T, MK extends keyof (MP | MR) ? MP[MK] : never, MK extends keyof (MP | MR) ? MR[MK] : never, QP, QR, MP, MR>, 'onCompleted' | 'onSuccess' | 'onError'> & {
|
|
166
|
-
mutation: MK;
|
|
167
|
-
params: MK extends keyof (MP | MR) ? MP[MK] : never;
|
|
168
|
-
};
|
|
169
|
-
export type MutationResponse<R = unknown> = {
|
|
170
|
-
result?: R;
|
|
171
|
-
};
|
|
172
|
-
export type NormalizedMutationResponse<T extends Typenames = Typenames, R = unknown> = EntityChanges<T> & MutationResponse<R>;
|
|
173
|
-
export type MutationResult<R = unknown> = {
|
|
174
|
-
error?: unknown;
|
|
175
|
-
aborted?: true;
|
|
176
|
-
result?: R;
|
|
177
|
-
};
|
|
178
|
-
export type MutationState<T extends Typenames, P, R> = {
|
|
179
|
-
/** Set when fetch is currently in progress. */
|
|
180
|
-
loading?: Promise<NormalizedQueryResponse<T, R>>;
|
|
181
|
-
/** Result of the latest successfull response. */
|
|
182
|
-
result?: R;
|
|
183
|
-
/** Error of the latest response. */
|
|
184
|
-
error?: Error;
|
|
185
|
-
/** Parameters of the latest request. */
|
|
186
|
-
params?: P;
|
|
187
|
-
};
|
package/dist/types.js
DELETED
package/dist/useMutation.d.ts
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { Actions } from './createActions';
|
|
2
|
-
import { Selectors } from './createSelectors';
|
|
3
|
-
import { Cache, Key, MutateOptions, MutationState, Store, Typenames } from './types';
|
|
4
|
-
export declare const useMutation: <N extends string, T extends Typenames, QP, QR, MP, MR, MK extends keyof (MP & MR)>(cache: Cache<N, T, QP, QR, MP, MR>, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>, options: Omit<MutateOptions<N, T, QP, QR, MP, MR, MK>, "params">, abortControllers: WeakMap<Store, Record<Key, AbortController>>) => readonly [(params: MK extends keyof MP & keyof MR ? MP[MK] : never) => Promise<import("./types").MutationResult<MK extends infer T_1 ? T_1 extends MK ? T_1 extends keyof MP & keyof MR ? MR[T_1] : never : never : never>>, MutationState<T, MK extends keyof MP & keyof MR ? MP[MK] : never, MK extends keyof MP & keyof MR ? MP[MK] : never>, () => boolean];
|
package/dist/useMutation.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.useMutation = void 0;
|
|
13
|
-
const react_1 = require("react");
|
|
14
|
-
const mutate_1 = require("./mutate");
|
|
15
|
-
const utilsAndConstants_1 = require("./utilsAndConstants");
|
|
16
|
-
const useMutation = (cache, actions, selectors, options, abortControllers) => {
|
|
17
|
-
var _a;
|
|
18
|
-
const { mutation: mutationKey, onCompleted, onSuccess, onError } = options;
|
|
19
|
-
const store = cache.storeHooks.useStore();
|
|
20
|
-
// Using single useMemo for performance reasons
|
|
21
|
-
const [mutationStateSelector, mutate, abort] = (0, react_1.useMemo)(() => {
|
|
22
|
-
return [
|
|
23
|
-
// mutationStateSelector
|
|
24
|
-
(state) => {
|
|
25
|
-
cache.options.logsEnabled &&
|
|
26
|
-
(0, utilsAndConstants_1.log)('mutationStateSelector', {
|
|
27
|
-
state,
|
|
28
|
-
cacheState: cache.cacheStateSelector(state),
|
|
29
|
-
});
|
|
30
|
-
return cache.cacheStateSelector(state).mutations[mutationKey];
|
|
31
|
-
},
|
|
32
|
-
// mutate
|
|
33
|
-
(params) => __awaiter(void 0, void 0, void 0, function* () {
|
|
34
|
-
return yield (0, mutate_1.mutate)('useMutation.mutate', store, cache, actions, selectors, mutationKey, params, abortControllers,
|
|
35
|
-
// @ts-expect-error fix later
|
|
36
|
-
onCompleted, onSuccess, onError);
|
|
37
|
-
}),
|
|
38
|
-
// abort
|
|
39
|
-
() => {
|
|
40
|
-
var _a;
|
|
41
|
-
const abortController = (_a = abortControllers.get(store)) === null || _a === void 0 ? void 0 : _a[mutationKey];
|
|
42
|
-
if (abortController === undefined || abortController.signal.aborted) {
|
|
43
|
-
return false;
|
|
44
|
-
}
|
|
45
|
-
abortController.abort();
|
|
46
|
-
store.dispatch(actions.updateMutationStateAndEntities(mutationKey, { loading: undefined }));
|
|
47
|
-
return true;
|
|
48
|
-
},
|
|
49
|
-
];
|
|
50
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
51
|
-
}, [mutationKey, store]);
|
|
52
|
-
// @ts-expect-error fix later
|
|
53
|
-
const mutationState = (_a = cache.storeHooks.useSelector(mutationStateSelector)) !== null && _a !== void 0 ? _a : utilsAndConstants_1.EMPTY_OBJECT;
|
|
54
|
-
cache.options.logsEnabled &&
|
|
55
|
-
(0, utilsAndConstants_1.log)('useMutation', {
|
|
56
|
-
options,
|
|
57
|
-
mutationState,
|
|
58
|
-
});
|
|
59
|
-
return [mutate, mutationState, abort];
|
|
60
|
-
};
|
|
61
|
-
exports.useMutation = useMutation;
|
package/dist/useQuery.d.ts
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { Actions } from './createActions';
|
|
2
|
-
import { Selectors } from './createSelectors';
|
|
3
|
-
import { Cache, QueryOptions, QueryState, Typenames, UseQueryOptions } from './types';
|
|
4
|
-
export declare const useQuery: <N extends string, T extends Typenames, QP, QR, MP, MR, QK extends keyof (QP & QR)>(cache: Cache<N, T, QP, QR, MP, MR>, actions: Actions<N, T, QP, QR, MP, MR>, selectors: Selectors<N, T, QP, QR, MP, MR>, options: UseQueryOptions<N, T, QK, QP, QR, MP, MR>) => readonly [Omit<QueryState<T, QK extends keyof QP & keyof QR ? QP[QK] : never, QK extends keyof QP & keyof QR ? QR[QK] : never>, "expiresAt">, (options?: Partial<Pick<QueryOptions<N, T, QP, QR, QK, MP, MR>, "params" | "onlyIfExpired">>) => Promise<import("./types").QueryResult<QK extends infer T_1 ? T_1 extends QK ? T_1 extends keyof QP & keyof QR ? QR[T_1] : never : never : never>>];
|
package/dist/useQuery.js
DELETED
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.useQuery = void 0;
|
|
13
|
-
const react_1 = require("react");
|
|
14
|
-
const query_1 = require("./query");
|
|
15
|
-
const utilsAndConstants_1 = require("./utilsAndConstants");
|
|
16
|
-
const useQuery = (cache, actions, selectors, options) => {
|
|
17
|
-
var _a, _b, _c, _d, _e;
|
|
18
|
-
const { query: queryKey, skipFetch = false, params, secondsToLive, selectorComparer, fetchPolicy = (_a = cache.queries[queryKey].fetchPolicy) !== null && _a !== void 0 ? _a : cache.globals.queries.fetchPolicy, mergeResults, onCompleted, onSuccess, onError, } = options;
|
|
19
|
-
const { selectQueryState } = selectors;
|
|
20
|
-
const queryInfo = cache.queries[queryKey];
|
|
21
|
-
const logsEnabled = cache.options.logsEnabled;
|
|
22
|
-
const getCacheKey = (_b = queryInfo.getCacheKey) !== null && _b !== void 0 ? _b : (utilsAndConstants_1.defaultGetCacheKey);
|
|
23
|
-
const comparer = selectorComparer === undefined
|
|
24
|
-
? (_d = (_c = queryInfo.selectorComparer) !== null && _c !== void 0 ? _c : cache.globals.queries.selectorComparer) !== null && _d !== void 0 ? _d : defaultStateComparer
|
|
25
|
-
: typeof selectorComparer === 'function'
|
|
26
|
-
? selectorComparer
|
|
27
|
-
: (0, utilsAndConstants_1.createStateComparer)(selectorComparer);
|
|
28
|
-
const store = cache.storeHooks.useStore();
|
|
29
|
-
// @ts-expect-error fix types later
|
|
30
|
-
const cacheKey = getCacheKey(params);
|
|
31
|
-
/** Fetch query with the new parameters, or refetch with the same if parameters not provided. */
|
|
32
|
-
const performFetch = (0, react_1.useCallback)((options) => __awaiter(void 0, void 0, void 0, function* () {
|
|
33
|
-
const paramsPassed = options && 'params' in options;
|
|
34
|
-
return yield (0, query_1.query)('useQuery.fetch', store, cache, actions, selectors, queryKey,
|
|
35
|
-
// @ts-expect-error fix later
|
|
36
|
-
paramsPassed ? getCacheKey(options.params) : cacheKey, paramsPassed ? options.params : params, // params type can also have null | undefined, thats why we don't check for it here
|
|
37
|
-
secondsToLive, options === null || options === void 0 ? void 0 : options.onlyIfExpired,
|
|
38
|
-
// @ts-expect-error fix later
|
|
39
|
-
mergeResults, onCompleted, onSuccess, onError);
|
|
40
|
-
}),
|
|
41
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
42
|
-
[store, queryKey, cacheKey]);
|
|
43
|
-
/** Query state */
|
|
44
|
-
const queryState = (_e = cache.storeHooks.useSelector((state) => {
|
|
45
|
-
return selectQueryState(state, queryKey, cacheKey); // TODO proper type
|
|
46
|
-
}, comparer)) !== null && _e !== void 0 ? _e : utilsAndConstants_1.EMPTY_OBJECT;
|
|
47
|
-
(0, react_1.useEffect)(() => {
|
|
48
|
-
if (skipFetch) {
|
|
49
|
-
logsEnabled && (0, utilsAndConstants_1.log)('useQuery.useEffect skip fetch', { skipFetch, queryKey, cacheKey });
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
const expired = queryState.expiresAt != null && queryState.expiresAt <= Date.now();
|
|
53
|
-
if (!fetchPolicy(expired,
|
|
54
|
-
// @ts-expect-error params
|
|
55
|
-
params, queryState, store, selectors)) {
|
|
56
|
-
logsEnabled &&
|
|
57
|
-
(0, utilsAndConstants_1.log)('useQuery.useEffect skip fetch due to fetch policy', {
|
|
58
|
-
queryState,
|
|
59
|
-
expired,
|
|
60
|
-
queryKey,
|
|
61
|
-
cacheKey,
|
|
62
|
-
});
|
|
63
|
-
return;
|
|
64
|
-
}
|
|
65
|
-
performFetch();
|
|
66
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
67
|
-
}, [cacheKey, skipFetch]);
|
|
68
|
-
logsEnabled &&
|
|
69
|
-
(0, utilsAndConstants_1.log)('useQuery', {
|
|
70
|
-
cacheKey,
|
|
71
|
-
options,
|
|
72
|
-
queryState,
|
|
73
|
-
});
|
|
74
|
-
return [queryState, performFetch];
|
|
75
|
-
};
|
|
76
|
-
exports.useQuery = useQuery;
|
|
77
|
-
const defaultStateComparer = (0, utilsAndConstants_1.createStateComparer)(['result', 'loading', 'params', 'error']);
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import type { CacheOptions, EntitiesMap, EntityChanges, Key, QueryState, QueryStateComparer, Typenames } from './types';
|
|
2
|
-
export declare const PACKAGE_SHORT_NAME = "rrc";
|
|
3
|
-
export declare const optionalUtils: {
|
|
4
|
-
deepEqual?: (a: any, b: any) => boolean;
|
|
5
|
-
};
|
|
6
|
-
export declare const IS_DEV: boolean;
|
|
7
|
-
export declare const EMPTY_OBJECT: Readonly<{}>;
|
|
8
|
-
export declare const EMPTY_ARRAY: readonly never[];
|
|
9
|
-
export declare const NOOP: () => void;
|
|
10
|
-
export declare const defaultGetCacheKey: <P = unknown>(params: P) => Key;
|
|
11
|
-
export declare const log: (tag: string, data?: unknown) => void;
|
|
12
|
-
export declare const FetchPolicy: {
|
|
13
|
-
/** Only if cache does not exist (result is undefined) or expired. */
|
|
14
|
-
NoCacheOrExpired: <T extends Typenames = Typenames, P = unknown, R = unknown>(expired: boolean, _params: P, state: QueryState<T, P, R>) => boolean;
|
|
15
|
-
/** Every fetch trigger. */
|
|
16
|
-
Always: () => boolean;
|
|
17
|
-
};
|
|
18
|
-
export declare const applyEntityChanges: <T extends Typenames>(entities: EntitiesMap<T>, changes: EntityChanges<T>, options: CacheOptions) => EntitiesMap<T> | undefined;
|
|
19
|
-
export declare const isEmptyObject: (o: object) => boolean;
|
|
20
|
-
export declare const createStateComparer: <T extends Typenames = Typenames, Q = unknown, P = unknown>(fields: (keyof QueryState<T, Q, P>)[]) => QueryStateComparer<T, Q, P>;
|
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createStateComparer = exports.isEmptyObject = exports.applyEntityChanges = exports.FetchPolicy = exports.log = exports.defaultGetCacheKey = exports.NOOP = exports.EMPTY_ARRAY = exports.EMPTY_OBJECT = exports.IS_DEV = exports.optionalUtils = exports.PACKAGE_SHORT_NAME = void 0;
|
|
4
|
-
exports.PACKAGE_SHORT_NAME = 'rrc';
|
|
5
|
-
exports.optionalUtils = {
|
|
6
|
-
deepEqual: undefined,
|
|
7
|
-
};
|
|
8
|
-
try {
|
|
9
|
-
exports.optionalUtils.deepEqual = require('fast-deep-equal/es6');
|
|
10
|
-
}
|
|
11
|
-
catch (_a) {
|
|
12
|
-
console.debug(exports.PACKAGE_SHORT_NAME + ': fast-deep-equal optional dependency was not installed');
|
|
13
|
-
}
|
|
14
|
-
exports.IS_DEV = (() => {
|
|
15
|
-
try {
|
|
16
|
-
// @ts-expect-error __DEV__ is only for React Native
|
|
17
|
-
return __DEV__;
|
|
18
|
-
}
|
|
19
|
-
catch (e) {
|
|
20
|
-
return process.env.NODE_ENV === 'development';
|
|
21
|
-
}
|
|
22
|
-
})();
|
|
23
|
-
exports.EMPTY_OBJECT = Object.freeze({});
|
|
24
|
-
exports.EMPTY_ARRAY = Object.freeze([]);
|
|
25
|
-
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
|
26
|
-
const NOOP = () => { };
|
|
27
|
-
exports.NOOP = NOOP;
|
|
28
|
-
const defaultGetCacheKey = (params) => {
|
|
29
|
-
switch (typeof params) {
|
|
30
|
-
case 'string':
|
|
31
|
-
case 'symbol':
|
|
32
|
-
return params;
|
|
33
|
-
case 'object':
|
|
34
|
-
return JSON.stringify(params);
|
|
35
|
-
default:
|
|
36
|
-
return String(params);
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
exports.defaultGetCacheKey = defaultGetCacheKey;
|
|
40
|
-
const log = (tag, data) => {
|
|
41
|
-
console.debug(`@${exports.PACKAGE_SHORT_NAME} [${tag}]`, data);
|
|
42
|
-
};
|
|
43
|
-
exports.log = log;
|
|
44
|
-
exports.FetchPolicy = {
|
|
45
|
-
/** Only if cache does not exist (result is undefined) or expired. */
|
|
46
|
-
NoCacheOrExpired: (expired, _params, state) => {
|
|
47
|
-
return expired || state.result === undefined;
|
|
48
|
-
},
|
|
49
|
-
/** Every fetch trigger. */
|
|
50
|
-
Always: () => true,
|
|
51
|
-
};
|
|
52
|
-
const applyEntityChanges = (entities, changes, options) => {
|
|
53
|
-
var _a, _b, _c, _d;
|
|
54
|
-
if (changes.merge && changes.entities) {
|
|
55
|
-
console.warn('react-redux-cache.applyEntityChanges: merge and entities should not be both set');
|
|
56
|
-
}
|
|
57
|
-
const { merge = changes.entities, replace, remove } = changes;
|
|
58
|
-
if (!merge && !replace && !remove) {
|
|
59
|
-
return undefined;
|
|
60
|
-
}
|
|
61
|
-
const deepEqual = options.deepComparisonEnabled ? exports.optionalUtils.deepEqual : undefined;
|
|
62
|
-
let result;
|
|
63
|
-
// TODO refactor to remove this Set
|
|
64
|
-
const typenames = new Set([
|
|
65
|
-
...(changes.entities ? Object.keys(changes.entities) : exports.EMPTY_ARRAY),
|
|
66
|
-
...(changes.merge ? Object.keys(changes.merge) : exports.EMPTY_ARRAY),
|
|
67
|
-
...(changes.remove ? Object.keys(changes.remove) : exports.EMPTY_ARRAY),
|
|
68
|
-
...(changes.replace ? Object.keys(changes.replace) : exports.EMPTY_ARRAY),
|
|
69
|
-
]);
|
|
70
|
-
for (const typename of typenames) {
|
|
71
|
-
const entitiesToMerge = merge === null || merge === void 0 ? void 0 : merge[typename];
|
|
72
|
-
const entitiesToReplace = replace === null || replace === void 0 ? void 0 : replace[typename];
|
|
73
|
-
const entitiesToRemove = remove === null || remove === void 0 ? void 0 : remove[typename];
|
|
74
|
-
if (!entitiesToMerge && !entitiesToReplace && !(entitiesToRemove === null || entitiesToRemove === void 0 ? void 0 : entitiesToRemove.length)) {
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
// check for key intersection
|
|
78
|
-
if (options.additionalValidation) {
|
|
79
|
-
const mergeIds = entitiesToMerge && Object.keys(entitiesToMerge);
|
|
80
|
-
const replaceIds = entitiesToReplace && Object.keys(entitiesToReplace);
|
|
81
|
-
const idsSet = new Set(mergeIds);
|
|
82
|
-
replaceIds === null || replaceIds === void 0 ? void 0 : replaceIds.forEach((id) => idsSet.add(id));
|
|
83
|
-
entitiesToRemove === null || entitiesToRemove === void 0 ? void 0 : entitiesToRemove.forEach((id) => idsSet.add(String(id))); // String() because Object.keys always returns strings
|
|
84
|
-
const totalKeysInResponse = ((_a = mergeIds === null || mergeIds === void 0 ? void 0 : mergeIds.length) !== null && _a !== void 0 ? _a : 0) + ((_b = replaceIds === null || replaceIds === void 0 ? void 0 : replaceIds.length) !== null && _b !== void 0 ? _b : 0) + ((_c = entitiesToRemove === null || entitiesToRemove === void 0 ? void 0 : entitiesToRemove.length) !== null && _c !== void 0 ? _c : 0);
|
|
85
|
-
if (totalKeysInResponse !== 0 && idsSet.size !== totalKeysInResponse) {
|
|
86
|
-
console.warn('react-redux-cache.applyEntityChanges: merge, replace and remove changes have intersections for: ' +
|
|
87
|
-
typename);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
const oldEntities = (_d = entities[typename]) !== null && _d !== void 0 ? _d : exports.EMPTY_OBJECT;
|
|
91
|
-
let newEntities;
|
|
92
|
-
// remove
|
|
93
|
-
entitiesToRemove === null || entitiesToRemove === void 0 ? void 0 : entitiesToRemove.forEach((id) => {
|
|
94
|
-
if (oldEntities[id]) {
|
|
95
|
-
newEntities !== null && newEntities !== void 0 ? newEntities : (newEntities = Object.assign({}, oldEntities));
|
|
96
|
-
delete newEntities[id];
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
// replace
|
|
100
|
-
if (entitiesToReplace) {
|
|
101
|
-
for (const id in entitiesToReplace) {
|
|
102
|
-
const newEntity = entitiesToReplace[id];
|
|
103
|
-
if (!(deepEqual === null || deepEqual === void 0 ? void 0 : deepEqual(oldEntities[id], newEntity))) {
|
|
104
|
-
newEntities !== null && newEntities !== void 0 ? newEntities : (newEntities = Object.assign({}, oldEntities));
|
|
105
|
-
newEntities[id] = newEntity;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
// merge
|
|
110
|
-
if (entitiesToMerge) {
|
|
111
|
-
for (const id in entitiesToMerge) {
|
|
112
|
-
const oldEntity = oldEntities[id];
|
|
113
|
-
const newEntity = Object.assign(Object.assign({}, oldEntity), entitiesToMerge[id]);
|
|
114
|
-
if (!(deepEqual === null || deepEqual === void 0 ? void 0 : deepEqual(oldEntity, newEntity))) {
|
|
115
|
-
newEntities !== null && newEntities !== void 0 ? newEntities : (newEntities = Object.assign({}, oldEntities));
|
|
116
|
-
newEntities[id] = newEntity;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
if (!newEntities) {
|
|
121
|
-
continue;
|
|
122
|
-
}
|
|
123
|
-
result !== null && result !== void 0 ? result : (result = Object.assign({}, entities));
|
|
124
|
-
// @ts-expect-error fix later
|
|
125
|
-
result[typename] = newEntities;
|
|
126
|
-
}
|
|
127
|
-
options.logsEnabled &&
|
|
128
|
-
(0, exports.log)('applyEntityChanges', {
|
|
129
|
-
entities,
|
|
130
|
-
changes,
|
|
131
|
-
options,
|
|
132
|
-
result,
|
|
133
|
-
});
|
|
134
|
-
return result;
|
|
135
|
-
};
|
|
136
|
-
exports.applyEntityChanges = applyEntityChanges;
|
|
137
|
-
const isEmptyObject = (o) => {
|
|
138
|
-
for (const _ in o) {
|
|
139
|
-
return false;
|
|
140
|
-
}
|
|
141
|
-
return true;
|
|
142
|
-
};
|
|
143
|
-
exports.isEmptyObject = isEmptyObject;
|
|
144
|
-
const createStateComparer = (fields) => {
|
|
145
|
-
return (x, y) => {
|
|
146
|
-
if (x === y) {
|
|
147
|
-
return true;
|
|
148
|
-
}
|
|
149
|
-
if (x === undefined || y === undefined) {
|
|
150
|
-
return false;
|
|
151
|
-
}
|
|
152
|
-
for (let i = 0; i < fields.length; i += 1) {
|
|
153
|
-
const key = fields[i];
|
|
154
|
-
if (x[key] !== y[key]) {
|
|
155
|
-
return false;
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
return true;
|
|
159
|
-
};
|
|
160
|
-
};
|
|
161
|
-
exports.createStateComparer = createStateComparer;
|