@ventlio/tanstack-query 0.5.4 → 0.5.6

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.
Files changed (76) hide show
  1. package/dist/config/bootstrapQueryRequest.d.ts +4 -4
  2. package/dist/config/bootstrapQueryRequest.js +15 -15
  3. package/dist/config/config.interface.d.ts +4 -4
  4. package/dist/config/index.d.ts +6 -6
  5. package/dist/config/useEnvironmentVariables.d.ts +2 -2
  6. package/dist/config/useEnvironmentVariables.js +8 -8
  7. package/dist/config/useQueryConfig.d.ts +2 -2
  8. package/dist/config/useQueryConfig.js +5 -5
  9. package/dist/config/useQueryHeaders.d.ts +2 -2
  10. package/dist/config/useQueryHeaders.js +9 -9
  11. package/dist/config/useReactNativeEnv.d.ts +5 -5
  12. package/dist/config/useReactNativeEnv.js +6 -6
  13. package/dist/helpers/index.d.ts +2 -2
  14. package/dist/helpers/scrollToTop.d.ts +1 -1
  15. package/dist/helpers/scrollToTop.js +5 -5
  16. package/dist/helpers/timeFuncs.d.ts +1 -1
  17. package/dist/helpers/timeFuncs.js +7 -7
  18. package/dist/hooks/index.d.ts +1 -1
  19. package/dist/hooks/useUploadProgress.d.ts +5 -5
  20. package/dist/hooks/useUploadProgress.js +8 -8
  21. package/dist/index.d.ts +8 -8
  22. package/dist/index.mjs +827 -830
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/model/index.d.ts +4 -4
  25. package/dist/model/model.interface.d.ts +11 -11
  26. package/dist/model/useKeyTrackerModel.d.ts +4 -4
  27. package/dist/model/useKeyTrackerModel.js +14 -14
  28. package/dist/model/useQueryModel.d.ts +2 -2
  29. package/dist/model/useQueryModel.js +115 -115
  30. package/dist/model/useRefetchQuery.d.ts +3 -3
  31. package/dist/model/useRefetchQuery.js +10 -10
  32. package/dist/queries/index.d.ts +6 -6
  33. package/dist/queries/queries.interface.d.ts +17 -17
  34. package/dist/queries/useDeleteRequest.d.ts +60 -60
  35. package/dist/queries/useDeleteRequest.js +72 -71
  36. package/dist/queries/useDeleteRequest.js.map +1 -1
  37. package/dist/queries/useGetInfiniteRequest.d.ts +108 -110
  38. package/dist/queries/useGetInfiniteRequest.js +103 -102
  39. package/dist/queries/useGetInfiniteRequest.js.map +1 -1
  40. package/dist/queries/useGetRequest.d.ts +73 -74
  41. package/dist/queries/useGetRequest.js +129 -133
  42. package/dist/queries/useGetRequest.js.map +1 -1
  43. package/dist/queries/usePatchRequest.d.ts +86 -86
  44. package/dist/queries/usePatchRequest.js +70 -70
  45. package/dist/queries/usePostRequest.d.ts +149 -157
  46. package/dist/queries/usePostRequest.js +77 -78
  47. package/dist/queries/usePostRequest.js.map +1 -1
  48. package/dist/queries/usePutRequest.d.ts +86 -86
  49. package/dist/request/axios-instance.d.ts +3 -3
  50. package/dist/request/axios-instance.js +6 -6
  51. package/dist/request/buildFormData.d.ts +1 -1
  52. package/dist/request/buildFormData.js +40 -40
  53. package/dist/request/index.d.ts +6 -6
  54. package/dist/request/make-request.d.ts +2 -2
  55. package/dist/request/make-request.js +80 -80
  56. package/dist/request/request.enum.d.ts +11 -11
  57. package/dist/request/request.enum.js +12 -12
  58. package/dist/request/request.interface.d.ts +48 -48
  59. package/dist/request/transformer.d.ts +7 -7
  60. package/dist/request/transformer.js +18 -18
  61. package/dist/stores/index.d.ts +2 -2
  62. package/dist/stores/useHeaderStore.d.ts +7 -7
  63. package/dist/stores/useHeaderStore.js +5 -5
  64. package/dist/stores/usePauseFutureRequests.d.ts +7 -7
  65. package/dist/stores/usePauseFutureRequests.js +13 -13
  66. package/dist/types/index.d.ts +27 -29
  67. package/package.json +2 -2
  68. package/src/queries/useDeleteRequest.ts +13 -14
  69. package/src/queries/useGetInfiniteRequest.ts +17 -19
  70. package/src/queries/useGetRequest.ts +29 -36
  71. package/src/queries/usePatchRequest.ts +24 -22
  72. package/src/queries/usePostRequest.ts +20 -23
  73. package/src/queries/usePutRequest.ts +19 -22
  74. package/src/request/make-request.ts +2 -2
  75. package/src/request/transformer.ts +1 -1
  76. package/src/types/index.ts +5 -4
package/dist/index.mjs CHANGED
@@ -6,880 +6,877 @@ import result from 'lodash.result';
6
6
  import lodashSet from 'lodash.set';
7
7
  import axios from 'axios';
8
8
 
9
- const bootstrapQueryRequest = (queryClient, options) => {
10
- // make query config doesn't expire
11
- // set default query config
12
- const defaultMeta = {
13
- headers: {
14
- Authorization: ``,
15
- },
16
- options,
17
- };
18
- queryClient.setDefaultOptions({
19
- queries: {
20
- meta: defaultMeta,
21
- },
22
- mutations: { meta: defaultMeta },
23
- });
9
+ const bootstrapQueryRequest = (queryClient, options) => {
10
+ // make query config doesn't expire
11
+ // set default query config
12
+ const defaultMeta = {
13
+ headers: {
14
+ Authorization: ``,
15
+ },
16
+ options,
17
+ };
18
+ queryClient.setDefaultOptions({
19
+ queries: {
20
+ meta: defaultMeta,
21
+ },
22
+ mutations: { meta: defaultMeta },
23
+ });
24
24
  };
25
25
 
26
- const useQueryConfig = () => {
27
- const queryClient = useQueryClient();
28
- const mutationMeta = (queryClient.getDefaultOptions().mutations?.meta ?? {});
29
- const queryMeta = (queryClient.getDefaultOptions().queries?.meta ?? {});
30
- return { ...queryMeta, ...mutationMeta };
26
+ const useQueryConfig = () => {
27
+ const queryClient = useQueryClient();
28
+ const mutationMeta = (queryClient.getDefaultOptions().mutations?.meta ?? {});
29
+ const queryMeta = (queryClient.getDefaultOptions().queries?.meta ?? {});
30
+ return { ...queryMeta, ...mutationMeta };
31
31
  };
32
32
 
33
- const useReactNativeEnv = () => {
34
- const config = useQueryConfig();
35
- const appUrl = config.options?.environments?.appBaseUrl;
36
- const appTimeout = config.options?.environments?.appTimeout;
37
- const isApp = config.options?.context === 'app';
38
- return { appUrl, appTimeout, isApp };
33
+ const useReactNativeEnv = () => {
34
+ const config = useQueryConfig();
35
+ const appUrl = config.options?.environments?.appBaseUrl;
36
+ const appTimeout = config.options?.environments?.appTimeout;
37
+ const isApp = config.options?.context === 'app';
38
+ return { appUrl, appTimeout, isApp };
39
39
  };
40
40
 
41
- const useEnvironmentVariables = () => {
42
- const { appTimeout, appUrl } = useReactNativeEnv();
43
- const url = process.env.REACT_APP_API_URL ?? process.env.NEXT_PUBLIC_API_URL ?? appUrl;
44
- const timeout = process.env.REACT_APP_API_TIMEOUT ?? process.env.NEXT_PUBLIC_API_TIMEOUT ?? appTimeout;
45
- return {
46
- API_URL: url,
47
- TIMEOUT: Number(timeout),
48
- };
41
+ const useEnvironmentVariables = () => {
42
+ const { appTimeout, appUrl } = useReactNativeEnv();
43
+ const url = process.env.REACT_APP_API_URL ?? process.env.NEXT_PUBLIC_API_URL ?? appUrl;
44
+ const timeout = process.env.REACT_APP_API_TIMEOUT ?? process.env.NEXT_PUBLIC_API_TIMEOUT ?? appTimeout;
45
+ return {
46
+ API_URL: url,
47
+ TIMEOUT: Number(timeout),
48
+ };
49
49
  };
50
50
 
51
- const useHeaderStore = create((set) => ({
52
- headers: undefined,
53
- setHeader(headers) {
54
- set({ headers });
55
- },
51
+ const useHeaderStore = create((set) => ({
52
+ headers: undefined,
53
+ setHeader(headers) {
54
+ set({ headers });
55
+ },
56
56
  }));
57
57
 
58
- const usePauseFutureRequests = create((set) => {
59
- const pauseFutureQueries = (status) => {
60
- return set({ isFutureQueriesPaused: status });
61
- };
62
- const pauseFutureMutation = (status) => {
63
- return set({ isFutureQueriesPaused: status });
64
- };
65
- return {
66
- isFutureMutationsPaused: false,
67
- isFutureQueriesPaused: false,
68
- pauseFutureQueries,
69
- pauseFutureMutation,
70
- };
58
+ const usePauseFutureRequests = create((set) => {
59
+ const pauseFutureQueries = (status) => {
60
+ return set({ isFutureQueriesPaused: status });
61
+ };
62
+ const pauseFutureMutation = (status) => {
63
+ return set({ isFutureQueriesPaused: status });
64
+ };
65
+ return {
66
+ isFutureMutationsPaused: false,
67
+ isFutureQueriesPaused: false,
68
+ pauseFutureQueries,
69
+ pauseFutureMutation,
70
+ };
71
71
  });
72
72
 
73
- const useQueryHeaders = () => {
74
- const { headers, setHeader } = useHeaderStore();
75
- const getHeaders = () => {
76
- return headers;
77
- };
78
- const setQueryHeaders = (newHeaders) => {
79
- setHeader(newHeaders);
80
- };
81
- return { setQueryHeaders, getHeaders };
73
+ const useQueryHeaders = () => {
74
+ const { headers, setHeader } = useHeaderStore();
75
+ const getHeaders = () => {
76
+ return headers;
77
+ };
78
+ const setQueryHeaders = (newHeaders) => {
79
+ setHeader(newHeaders);
80
+ };
81
+ return { setQueryHeaders, getHeaders };
82
82
  };
83
83
 
84
- const scrollToTop = () => {
85
- window.scrollTo({
86
- top: 0,
87
- behavior: 'smooth',
88
- });
84
+ const scrollToTop = () => {
85
+ window.scrollTo({
86
+ top: 0,
87
+ behavior: 'smooth',
88
+ });
89
89
  };
90
90
 
91
- function getDateInFuture(days) {
92
- // Create a new Date object
93
- const date = new Date();
94
- // Add the specified number of days to the date
95
- date.setDate(date.getDate() + days);
96
- // Get the Unix timestamp of the date (in milliseconds)
97
- return date.getTime();
91
+ function getDateInFuture(days) {
92
+ // Create a new Date object
93
+ const date = new Date();
94
+ // Add the specified number of days to the date
95
+ date.setDate(date.getDate() + days);
96
+ // Get the Unix timestamp of the date (in milliseconds)
97
+ return date.getTime();
98
98
  }
99
99
 
100
- const useUploadProgress = () => {
101
- const [uploadProgressPercent, setUploadProgressPercent] = useState(0);
102
- const onUploadProgress = (progressEvent) => {
103
- const { loaded, total } = progressEvent;
104
- const percentage = Math.round((loaded / total) * 100);
105
- setUploadProgressPercent(percentage);
106
- };
107
- return { onUploadProgress, uploadProgressPercent };
100
+ const useUploadProgress = () => {
101
+ const [uploadProgressPercent, setUploadProgressPercent] = useState(0);
102
+ const onUploadProgress = (progressEvent) => {
103
+ const { loaded, total } = progressEvent;
104
+ const percentage = Math.round((loaded / total) * 100);
105
+ setUploadProgressPercent(percentage);
106
+ };
107
+ return { onUploadProgress, uploadProgressPercent };
108
108
  };
109
109
 
110
- const useKeyTrackerModel = (keyTracker) => {
111
- const queryClient = useQueryClient();
112
- const getQueryKey = (innerKeyTracker) => {
113
- const queryKey = queryClient.getQueryData([innerKeyTracker ?? keyTracker]);
114
- return queryKey;
115
- };
116
- const refetchQuery = async (innerKeyTracker) => {
117
- const queryKey = getQueryKey(innerKeyTracker ?? keyTracker);
118
- await queryClient.refetchQueries({
119
- queryKey,
120
- exact: true,
121
- });
122
- };
123
- return { refetchQuery, getQueryKey };
110
+ const useKeyTrackerModel = (keyTracker) => {
111
+ const queryClient = useQueryClient();
112
+ const getQueryKey = (innerKeyTracker) => {
113
+ const queryKey = queryClient.getQueryData([innerKeyTracker ?? keyTracker]);
114
+ return queryKey;
115
+ };
116
+ const refetchQuery = async (innerKeyTracker) => {
117
+ const queryKey = getQueryKey(innerKeyTracker ?? keyTracker);
118
+ await queryClient.refetchQueries({
119
+ queryKey,
120
+ exact: true,
121
+ });
122
+ };
123
+ return { refetchQuery, getQueryKey };
124
124
  };
125
125
 
126
- const useQueryModel = (keyTracker) => {
127
- const queryClient = useQueryClient();
128
- const { getQueryKey } = useKeyTrackerModel(keyTracker);
129
- const queryKey = getQueryKey();
130
- const config = useQueryConfig();
131
- const add = (data, position, path) => {
132
- let records = (findAll(path) ?? []);
133
- if (!position || position === 'end') {
134
- records = [...records, data];
135
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
136
- }
137
- else if (position === 'start') {
138
- records = [data, ...records];
139
- }
140
- if (!path) {
141
- queryClient.setQueryData(queryKey, records);
142
- }
143
- else {
144
- const queryData = queryClient.getQueryData(queryKey) ?? {};
145
- queryClient.setQueryData(queryKey, lodashSet(queryData, path, records));
146
- }
147
- return data;
148
- };
149
- const findAll = (path) => {
150
- const data = queryClient.getQueryData(queryKey);
151
- if (!data) {
152
- return [];
153
- }
154
- if (!path) {
155
- return Array.isArray(data) ? data : [data];
156
- }
157
- return result(data, path, []);
158
- };
159
- const findMany = (selector, path) => {
160
- const data = (findAll(path) ?? []);
161
- return data.filter(selector);
162
- };
163
- const find = (id, path) => {
164
- const modelConfig = getModelConfig();
165
- if (!modelConfig?.idColumn) {
166
- return undefined;
167
- }
168
- const data = (findAll(path) ?? []);
169
- return data.find((record) => record[modelConfig.idColumn] === id);
170
- };
171
- const get = (path) => {
172
- let data = queryClient.getQueryData(queryKey);
173
- if (path) {
174
- data = result(data, path);
175
- }
176
- return data;
177
- };
178
- const set = (newData, path) => {
179
- if (path) {
180
- const data = get();
181
- newData = lodashSet(data, path, newData);
182
- }
183
- return queryClient.setQueryData(queryKey, () => newData);
184
- };
185
- const getModelConfig = () => {
186
- const { options } = config;
187
- const { modelConfig } = options ?? {};
188
- return modelConfig;
189
- };
190
- const update = (id, data, path) => {
191
- const oldData = (findAll(path) ?? []);
192
- const modelConfig = getModelConfig();
193
- if (!modelConfig?.idColumn) {
194
- return undefined;
195
- }
196
- const idColumn = modelConfig.idColumn;
197
- let updatedRecord = undefined;
198
- const newData = oldData.map((record) => {
199
- let dataRecord = record;
200
- if (dataRecord[idColumn] === id) {
201
- dataRecord = { ...dataRecord, ...data };
202
- updatedRecord = dataRecord;
203
- }
204
- return dataRecord;
205
- });
206
- if (!path) {
207
- queryClient.setQueryData(queryKey, newData);
208
- }
209
- else {
210
- const queryData = queryClient.getQueryData(queryKey) ?? {};
211
- queryClient.setQueryData(queryKey, lodashSet(queryData, path, newData));
212
- }
213
- return updatedRecord;
214
- };
215
- const remove = (id, path) => {
216
- const oldData = (findAll(path) ?? []);
217
- const modelConfig = getModelConfig();
218
- if (!modelConfig?.idColumn) {
219
- return false;
220
- }
221
- const idColumn = modelConfig.idColumn;
222
- let updated = false;
223
- const newData = oldData.filter((record) => {
224
- const dataRecord = record;
225
- if (dataRecord[idColumn] === id) {
226
- updated = true;
227
- return false;
228
- }
229
- return true;
230
- });
231
- if (!path) {
232
- queryClient.setQueryData(queryKey, newData);
233
- }
234
- else {
235
- const queryData = queryClient.getQueryData(queryKey) ?? {};
236
- queryClient.setQueryData(queryKey, lodashSet(queryData, path, newData));
237
- }
238
- return updated;
239
- };
240
- return { find, findAll, findMany, remove, update, add, get, set };
126
+ const useQueryModel = (keyTracker) => {
127
+ const queryClient = useQueryClient();
128
+ const { getQueryKey } = useKeyTrackerModel(keyTracker);
129
+ const queryKey = getQueryKey();
130
+ const config = useQueryConfig();
131
+ const add = (data, position, path) => {
132
+ let records = (findAll(path) ?? []);
133
+ if (!position || position === 'end') {
134
+ records = [...records, data];
135
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
136
+ }
137
+ else if (position === 'start') {
138
+ records = [data, ...records];
139
+ }
140
+ if (!path) {
141
+ queryClient.setQueryData(queryKey, records);
142
+ }
143
+ else {
144
+ const queryData = queryClient.getQueryData(queryKey) ?? {};
145
+ queryClient.setQueryData(queryKey, lodashSet(queryData, path, records));
146
+ }
147
+ return data;
148
+ };
149
+ const findAll = (path) => {
150
+ const data = queryClient.getQueryData(queryKey);
151
+ if (!data) {
152
+ return [];
153
+ }
154
+ if (!path) {
155
+ return Array.isArray(data) ? data : [data];
156
+ }
157
+ return result(data, path, []);
158
+ };
159
+ const findMany = (selector, path) => {
160
+ const data = (findAll(path) ?? []);
161
+ return data.filter(selector);
162
+ };
163
+ const find = (id, path) => {
164
+ const modelConfig = getModelConfig();
165
+ if (!modelConfig?.idColumn) {
166
+ return undefined;
167
+ }
168
+ const data = (findAll(path) ?? []);
169
+ return data.find((record) => record[modelConfig.idColumn] === id);
170
+ };
171
+ const get = (path) => {
172
+ let data = queryClient.getQueryData(queryKey);
173
+ if (path) {
174
+ data = result(data, path);
175
+ }
176
+ return data;
177
+ };
178
+ const set = (newData, path) => {
179
+ if (path) {
180
+ const data = get();
181
+ newData = lodashSet(data, path, newData);
182
+ }
183
+ return queryClient.setQueryData(queryKey, () => newData);
184
+ };
185
+ const getModelConfig = () => {
186
+ const { options } = config;
187
+ const { modelConfig } = options ?? {};
188
+ return modelConfig;
189
+ };
190
+ const update = (id, data, path) => {
191
+ const oldData = (findAll(path) ?? []);
192
+ const modelConfig = getModelConfig();
193
+ if (!modelConfig?.idColumn) {
194
+ return undefined;
195
+ }
196
+ const idColumn = modelConfig.idColumn;
197
+ let updatedRecord = undefined;
198
+ const newData = oldData.map((record) => {
199
+ let dataRecord = record;
200
+ if (dataRecord[idColumn] === id) {
201
+ dataRecord = { ...dataRecord, ...data };
202
+ updatedRecord = dataRecord;
203
+ }
204
+ return dataRecord;
205
+ });
206
+ if (!path) {
207
+ queryClient.setQueryData(queryKey, newData);
208
+ }
209
+ else {
210
+ const queryData = queryClient.getQueryData(queryKey) ?? {};
211
+ queryClient.setQueryData(queryKey, lodashSet(queryData, path, newData));
212
+ }
213
+ return updatedRecord;
214
+ };
215
+ const remove = (id, path) => {
216
+ const oldData = (findAll(path) ?? []);
217
+ const modelConfig = getModelConfig();
218
+ if (!modelConfig?.idColumn) {
219
+ return false;
220
+ }
221
+ const idColumn = modelConfig.idColumn;
222
+ let updated = false;
223
+ const newData = oldData.filter((record) => {
224
+ const dataRecord = record;
225
+ if (dataRecord[idColumn] === id) {
226
+ updated = true;
227
+ return false;
228
+ }
229
+ return true;
230
+ });
231
+ if (!path) {
232
+ queryClient.setQueryData(queryKey, newData);
233
+ }
234
+ else {
235
+ const queryData = queryClient.getQueryData(queryKey) ?? {};
236
+ queryClient.setQueryData(queryKey, lodashSet(queryData, path, newData));
237
+ }
238
+ return updated;
239
+ };
240
+ return { find, findAll, findMany, remove, update, add, get, set };
241
241
  };
242
242
 
243
- const useRefetchQuery = async (queryKey) => {
244
- const queryClient = useQueryClient();
245
- const refetchQuery = async (innerQueryKey) => {
246
- await queryClient.invalidateQueries({
247
- queryKey: innerQueryKey ?? queryKey,
248
- exact: true,
249
- }, { throwOnError: true, cancelRefetch: true });
250
- return queryClient.getQueriesData({ queryKey: innerQueryKey ?? queryKey });
251
- };
252
- return { refetchQuery };
243
+ const useRefetchQuery = async (queryKey) => {
244
+ const queryClient = useQueryClient();
245
+ const refetchQuery = async (innerQueryKey) => {
246
+ await queryClient.invalidateQueries({
247
+ queryKey: innerQueryKey ?? queryKey,
248
+ exact: true,
249
+ }, { throwOnError: true, cancelRefetch: true });
250
+ return queryClient.getQueriesData({ queryKey: innerQueryKey ?? queryKey });
251
+ };
252
+ return { refetchQuery };
253
253
  };
254
254
 
255
- const axiosInstance = ({ baseURL, timeout, headers }) => {
256
- return axios.create({
257
- baseURL,
258
- timeout,
259
- headers,
260
- });
255
+ const axiosInstance = ({ baseURL, timeout, headers }) => {
256
+ return axios.create({
257
+ baseURL,
258
+ timeout,
259
+ headers,
260
+ });
261
261
  };
262
262
 
263
- const buildFormData = (body) => {
264
- const formData = new FormData();
265
- const handleArrayValue = (key, value) => {
266
- for (const item of value) {
267
- if (item instanceof File) {
268
- formData.append(key, item);
269
- }
270
- else if (item instanceof Object) {
271
- formData.append(key, JSON.stringify(item));
272
- }
273
- else {
274
- formData.append(key, item);
275
- }
276
- }
277
- };
278
- const handleObjectValue = (key, value) => {
279
- if (value instanceof File) {
280
- formData.append(key, value);
281
- }
282
- else {
283
- formData.append(key, JSON.stringify(value));
284
- }
285
- };
286
- const handlePrimitiveValue = (key, value) => {
287
- formData.append(key, value);
288
- };
289
- const bodyKeys = Object.keys(body);
290
- bodyKeys.forEach((key) => {
291
- const inputValue = body[key];
292
- if (Array.isArray(inputValue) && inputValue.length > 0) {
293
- handleArrayValue(key, inputValue);
294
- }
295
- else if (inputValue instanceof Object) {
296
- handleObjectValue(key, inputValue);
297
- }
298
- else {
299
- handlePrimitiveValue(key, inputValue);
300
- }
301
- });
302
- return formData;
263
+ const buildFormData = (body) => {
264
+ const formData = new FormData();
265
+ const handleArrayValue = (key, value) => {
266
+ for (const item of value) {
267
+ if (item instanceof File) {
268
+ formData.append(key, item);
269
+ }
270
+ else if (item instanceof Object) {
271
+ formData.append(key, JSON.stringify(item));
272
+ }
273
+ else {
274
+ formData.append(key, item);
275
+ }
276
+ }
277
+ };
278
+ const handleObjectValue = (key, value) => {
279
+ if (value instanceof File) {
280
+ formData.append(key, value);
281
+ }
282
+ else {
283
+ formData.append(key, JSON.stringify(value));
284
+ }
285
+ };
286
+ const handlePrimitiveValue = (key, value) => {
287
+ formData.append(key, value);
288
+ };
289
+ const bodyKeys = Object.keys(body);
290
+ bodyKeys.forEach((key) => {
291
+ const inputValue = body[key];
292
+ if (Array.isArray(inputValue) && inputValue.length > 0) {
293
+ handleArrayValue(key, inputValue);
294
+ }
295
+ else if (inputValue instanceof Object) {
296
+ handleObjectValue(key, inputValue);
297
+ }
298
+ else {
299
+ handlePrimitiveValue(key, inputValue);
300
+ }
301
+ });
302
+ return formData;
303
303
  };
304
304
 
305
- var HttpMethod;
306
- (function (HttpMethod) {
307
- HttpMethod["GET"] = "GET";
308
- HttpMethod["POST"] = "POST";
309
- HttpMethod["PUT"] = "PUT";
310
- HttpMethod["PATCH"] = "PATCH";
311
- HttpMethod["DELETE"] = "DELETE";
312
- })(HttpMethod || (HttpMethod = {}));
313
- var ContentType;
314
- (function (ContentType) {
315
- ContentType["APPLICATION_JSON"] = "application/json";
316
- ContentType["MULTIPART_FORM_DATA"] = "multipart/form-data";
305
+ var HttpMethod;
306
+ (function (HttpMethod) {
307
+ HttpMethod["GET"] = "GET";
308
+ HttpMethod["POST"] = "POST";
309
+ HttpMethod["PUT"] = "PUT";
310
+ HttpMethod["PATCH"] = "PATCH";
311
+ HttpMethod["DELETE"] = "DELETE";
312
+ })(HttpMethod || (HttpMethod = {}));
313
+ var ContentType;
314
+ (function (ContentType) {
315
+ ContentType["APPLICATION_JSON"] = "application/json";
316
+ ContentType["MULTIPART_FORM_DATA"] = "multipart/form-data";
317
317
  })(ContentType || (ContentType = {}));
318
318
 
319
- //
320
- const errorTransformer = (data) => {
321
- return {
322
- timeStamp: new Date(),
323
- status: false,
324
- data: data.data,
325
- ...data,
326
- };
327
- };
328
- //
329
- const successTransformer = (data) => {
330
- return {
331
- message: data.message ?? 'Request successful',
332
- statusCode: data.statusCode,
333
- timeStamp: new Date(),
334
- status: true,
335
- data: data.data,
336
- };
319
+ //
320
+ const errorTransformer = (data) => {
321
+ return {
322
+ timeStamp: new Date(),
323
+ data: data.data,
324
+ ...data,
325
+ status: false,
326
+ };
327
+ };
328
+ //
329
+ const successTransformer = (data) => {
330
+ return {
331
+ message: data.message ?? 'Request successful',
332
+ statusCode: data.statusCode,
333
+ timeStamp: new Date(),
334
+ status: true,
335
+ data: data.data,
336
+ };
337
337
  };
338
338
 
339
- async function makeRequest({ body = {}, method = HttpMethod.GET, path, isFormData, headers = {}, baseURL, timeout, appFileConfig, onUploadProgress, }) {
340
- // check if file is included in mobile app environment and extract all file input to avoid
341
- // it being formatted to object using axios formData builder
342
- const isApp = appFileConfig?.isApp;
343
- const appFiles = isApp ? getAppFiles(body, appFileConfig.fileSelectors) : {};
344
- // configure body
345
- body = (isFormData ? axios.toFormData(body) : body);
346
- // configure request header1
347
- configureRequestHeader(isFormData, headers, isApp, appFiles, body);
348
- try {
349
- const axiosRequest = axiosInstance({ baseURL, headers, timeout });
350
- const axiosRequestConfig = {
351
- url: path,
352
- method,
353
- onUploadProgress,
354
- };
355
- if (Object.keys(body).length > 0 || (isFormData && !isApp && [...body.keys()].length > 0)) {
356
- axiosRequestConfig.data = body;
357
- }
358
- // send request
359
- const resp = await axiosRequest(axiosRequestConfig);
360
- // get response json
361
- const jsonResp = await resp.data;
362
- // get response code
363
- const responseCode = resp.status;
364
- if (responseCode > 299) {
365
- // server returned an error
366
- return errorTransformer({ ...jsonResp, statusCode: responseCode });
367
- }
368
- return successTransformer({
369
- statusCode: responseCode,
370
- ...jsonResp,
371
- status: resp.status,
372
- });
373
- }
374
- catch (error) {
375
- const errorData = error?.response?.data;
376
- return errorTransformer({
377
- statusCode: error.status,
378
- message: error.message,
379
- code: error.status || error.statusCode,
380
- ...errorData,
381
- });
382
- }
383
- }
384
- const configureRequestHeader = (isFormData, headers, isApp, appFiles, body) => {
385
- if (!isFormData) {
386
- headers['Content-Type'] = ContentType.APPLICATION_JSON;
387
- }
388
- else if (isApp) {
389
- headers['Content-Type'] = ContentType.MULTIPART_FORM_DATA;
390
- // add the app files
391
- for (const fileKey in appFiles) {
392
- const currentFile = appFiles[fileKey];
393
- if (Array.isArray(currentFile)) {
394
- for (const innerFile of currentFile) {
395
- body.append(fileKey, innerFile);
396
- }
397
- }
398
- else {
399
- body.append(fileKey, currentFile);
400
- }
401
- }
402
- }
403
- else {
404
- delete headers['Content-Type'];
405
- }
406
- };
407
- function getAppFiles(body, fileSelectors = []) {
408
- const files = {};
409
- if (body) {
410
- if (fileSelectors.length > 0) {
411
- //
412
- for (const fileKey of fileSelectors) {
413
- files[fileKey] = body[fileKey];
414
- delete body[fileKey];
415
- }
416
- }
417
- }
418
- return files;
339
+ async function makeRequest({ body = {}, method = HttpMethod.GET, path, isFormData, headers = {}, baseURL, timeout, appFileConfig, onUploadProgress, }) {
340
+ // check if file is included in mobile app environment and extract all file input to avoid
341
+ // it being formatted to object using axios formData builder
342
+ const isApp = appFileConfig?.isApp;
343
+ const appFiles = isApp ? getAppFiles(body, appFileConfig.fileSelectors) : {};
344
+ // configure body
345
+ body = (isFormData ? axios.toFormData(body) : body);
346
+ // configure request header1
347
+ configureRequestHeader(isFormData, headers, isApp, appFiles, body);
348
+ try {
349
+ const axiosRequest = axiosInstance({ baseURL, headers, timeout });
350
+ const axiosRequestConfig = {
351
+ url: path,
352
+ method,
353
+ onUploadProgress,
354
+ };
355
+ if (Object.keys(body).length > 0 || (isFormData && !isApp && [...body.keys()].length > 0)) {
356
+ axiosRequestConfig.data = body;
357
+ }
358
+ // send request
359
+ const resp = await axiosRequest(axiosRequestConfig);
360
+ // get response json
361
+ const jsonResp = await resp.data;
362
+ // get response code
363
+ const responseCode = resp.status;
364
+ if (responseCode > 299) {
365
+ // server returned an error
366
+ return errorTransformer({ ...jsonResp, statusCode: responseCode });
367
+ }
368
+ return successTransformer({
369
+ statusCode: responseCode,
370
+ ...jsonResp,
371
+ status: resp.status,
372
+ });
373
+ }
374
+ catch (error) {
375
+ const errorData = error?.response?.data;
376
+ return errorTransformer({
377
+ statusCode: error.status,
378
+ message: error.message,
379
+ code: error.status || error.statusCode,
380
+ ...errorData,
381
+ });
382
+ }
383
+ }
384
+ const configureRequestHeader = (isFormData, headers, isApp, appFiles, body) => {
385
+ if (!isFormData) {
386
+ headers['Content-Type'] = ContentType.APPLICATION_JSON;
387
+ }
388
+ else if (isApp) {
389
+ headers['Content-Type'] = ContentType.MULTIPART_FORM_DATA;
390
+ // add the app files
391
+ for (const fileKey in appFiles) {
392
+ const currentFile = appFiles[fileKey];
393
+ if (Array.isArray(currentFile)) {
394
+ for (const innerFile of currentFile) {
395
+ body.append(fileKey, innerFile);
396
+ }
397
+ }
398
+ else {
399
+ body.append(fileKey, currentFile);
400
+ }
401
+ }
402
+ }
403
+ else {
404
+ delete headers['Content-Type'];
405
+ }
406
+ };
407
+ function getAppFiles(body, fileSelectors = []) {
408
+ const files = {};
409
+ if (body) {
410
+ if (fileSelectors.length > 0) {
411
+ //
412
+ for (const fileKey of fileSelectors) {
413
+ files[fileKey] = body[fileKey];
414
+ delete body[fileKey];
415
+ }
416
+ }
417
+ }
418
+ return files;
419
419
  }
420
420
 
421
- const useDeleteRequest = (deleteOptions) => {
422
- const { baseUrl, headers } = deleteOptions ?? {};
423
- const [requestPath, setRequestPath] = useState('');
424
- const [options, setOptions] = useState();
425
- const { options: queryConfigOptions } = useQueryConfig();
426
- const [requestPayload, setRequestPayload] = useState();
427
- const isFutureQueriesPaused = usePauseFutureRequests((state) => state.isFutureQueriesPaused);
428
- const { API_URL, TIMEOUT } = useEnvironmentVariables();
429
- const globalHeaders = useHeaderStore((state) => state.headers);
430
- const sendRequest = async (res, rej, queryKey) => {
431
- const [url] = queryKey;
432
- const requestUrl = (url ?? requestPath);
433
- const requestOptions = {
434
- path: requestUrl,
435
- headers: { ...globalHeaders, ...headers },
436
- baseURL: baseUrl ?? API_URL,
437
- method: HttpMethod.DELETE,
438
- timeout: TIMEOUT,
439
- };
440
- let shouldContinue = true;
441
- if (queryConfigOptions?.queryMiddleware) {
442
- shouldContinue = await queryConfigOptions.queryMiddleware({ queryKey, ...requestOptions });
443
- }
444
- if (shouldContinue) {
445
- const postResponse = await makeRequest(requestOptions);
446
- if (postResponse.status) {
447
- res(postResponse);
448
- }
449
- else {
450
- rej(postResponse);
451
- }
452
- }
453
- else {
454
- rej(null);
455
- }
456
- };
457
- const query = useQuery({
458
- queryKey: [requestPath, {}],
459
- queryFn: ({ queryKey }) => new Promise((res, rej) => sendRequest(res, rej, queryKey)),
460
- enabled: false,
461
- ...options,
462
- });
463
- const updatedPathAsync = async (link) => {
464
- return setRequestPath(link);
465
- };
466
- const setOptionsAsync = async (fetchOptions) => {
467
- return setOptions(fetchOptions);
468
- };
469
- const destroy = async (link, internalDeleteOptions) => {
470
- if (!isFutureQueriesPaused) {
471
- // set enabled to be true for every delete
472
- internalDeleteOptions = internalDeleteOptions
473
- ? { ...internalDeleteOptions, queryKey: [link, {}], enabled: true }
474
- : { queryKey: [link, {}], enabled: true };
475
- await setOptionsAsync(internalDeleteOptions);
476
- await updatedPathAsync(link);
477
- return query.data;
478
- }
479
- else {
480
- setRequestPayload({ link, internalDeleteOptions });
481
- return undefined;
482
- }
483
- };
484
- useEffect(() => {
485
- if (!isFutureQueriesPaused && requestPayload) {
486
- destroy(requestPayload.link, requestPayload.internalDeleteOptions);
487
- setRequestPayload(undefined);
488
- }
489
- // eslint-disable-next-line react-hooks/exhaustive-deps
490
- }, [isFutureQueriesPaused]);
491
- return { destroy, ...query, isLoading: query.isLoading || isFutureQueriesPaused };
421
+ const useDeleteRequest = (deleteOptions) => {
422
+ const { baseUrl, headers } = deleteOptions ?? {};
423
+ const [requestPath, setRequestPath] = useState('');
424
+ const [options, setOptions] = useState();
425
+ const { options: queryConfigOptions } = useQueryConfig();
426
+ const [requestPayload, setRequestPayload] = useState();
427
+ const isFutureQueriesPaused = usePauseFutureRequests((state) => state.isFutureQueriesPaused);
428
+ const { API_URL, TIMEOUT } = useEnvironmentVariables();
429
+ const globalHeaders = useHeaderStore((state) => state.headers);
430
+ const sendRequest = async (res, rej, queryKey) => {
431
+ const [url] = queryKey;
432
+ const requestUrl = (url ?? requestPath);
433
+ const requestOptions = {
434
+ path: requestUrl,
435
+ headers: { ...globalHeaders, ...headers },
436
+ baseURL: baseUrl ?? API_URL,
437
+ method: HttpMethod.DELETE,
438
+ timeout: TIMEOUT,
439
+ };
440
+ let deleteResponse;
441
+ if (queryConfigOptions?.middleware) {
442
+ // perform global middleware
443
+ deleteResponse = await queryConfigOptions.middleware(async () => await makeRequest(requestOptions), {
444
+ path: requestUrl,
445
+ baseUrl: baseUrl ?? API_URL,
446
+ });
447
+ }
448
+ else {
449
+ deleteResponse = await makeRequest(requestOptions);
450
+ }
451
+ if (deleteResponse.status) {
452
+ res(deleteResponse);
453
+ }
454
+ else {
455
+ rej(deleteResponse);
456
+ }
457
+ };
458
+ const query = useQuery({
459
+ queryKey: [requestPath, {}],
460
+ queryFn: ({ queryKey }) => new Promise((res, rej) => sendRequest(res, rej, queryKey)),
461
+ enabled: false,
462
+ ...options,
463
+ });
464
+ const updatedPathAsync = async (link) => {
465
+ return setRequestPath(link);
466
+ };
467
+ const setOptionsAsync = async (fetchOptions) => {
468
+ return setOptions(fetchOptions);
469
+ };
470
+ const destroy = async (link, internalDeleteOptions) => {
471
+ if (!isFutureQueriesPaused) {
472
+ // set enabled to be true for every delete
473
+ internalDeleteOptions = internalDeleteOptions
474
+ ? { ...internalDeleteOptions, queryKey: [link, {}], enabled: true }
475
+ : { queryKey: [link, {}], enabled: true };
476
+ await setOptionsAsync(internalDeleteOptions);
477
+ await updatedPathAsync(link);
478
+ return query.data;
479
+ }
480
+ else {
481
+ setRequestPayload({ link, internalDeleteOptions });
482
+ return undefined;
483
+ }
484
+ };
485
+ useEffect(() => {
486
+ if (!isFutureQueriesPaused && requestPayload) {
487
+ destroy(requestPayload.link, requestPayload.internalDeleteOptions);
488
+ setRequestPayload(undefined);
489
+ }
490
+ // eslint-disable-next-line react-hooks/exhaustive-deps
491
+ }, [isFutureQueriesPaused]);
492
+ return { destroy, ...query, isLoading: query.isLoading || isFutureQueriesPaused };
492
493
  };
493
494
 
494
- const useGetInfiniteRequest = ({ path, load = false, queryOptions, keyTracker, baseUrl, headers, }) => {
495
- const { API_URL, TIMEOUT } = useEnvironmentVariables();
496
- const globalHeaders = useHeaderStore((state) => state.headers);
497
- const [requestPath, setRequestPath] = useState(path);
498
- const [options, setOptions] = useState(queryOptions);
499
- const { options: queryConfigOptions } = useQueryConfig();
500
- const [requestPayload, setRequestPayload] = useState();
501
- const isFutureQueriesPaused = usePauseFutureRequests((state) => state.isFutureQueriesPaused);
502
- let queryClient = useQueryClient();
503
- // eslint-disable-next-line react-hooks/exhaustive-deps
504
- queryClient = useMemo(() => queryClient, []);
505
- const sendRequest = async (res, rej, queryKey, pageParam) => {
506
- if (load) {
507
- // get request headers
508
- const requestOptions = {
509
- path: pageParam ?? requestPath,
510
- headers: { ...globalHeaders, ...headers },
511
- baseURL: baseUrl ?? API_URL,
512
- timeout: TIMEOUT,
513
- };
514
- let shouldContinue = true;
515
- if (queryConfigOptions?.queryMiddleware) {
516
- shouldContinue = await queryConfigOptions.queryMiddleware({ queryKey, ...requestOptions });
517
- }
518
- if (shouldContinue) {
519
- const getResponse = await makeRequest(requestOptions);
520
- if (getResponse.status) {
521
- res(getResponse);
522
- }
523
- else {
524
- rej(getResponse);
525
- }
526
- }
527
- else {
528
- rej(null);
529
- }
530
- }
531
- else {
532
- res(null);
533
- }
534
- };
535
- /**
536
- *
537
- * This pagination implementation is currently tied to our use case
538
- */
539
- const constructPaginationLink = (direction, lastPage) => {
540
- const [pathname, queryString] = requestPath.split('?');
541
- const queryParams = new URLSearchParams(queryString);
542
- const lastPageItem = lastPage.data.pagination[direction];
543
- queryParams.set('page', String(lastPageItem));
544
- return pathname + '?' + queryParams.toString();
545
- };
546
- const query = useInfiniteQuery({
547
- queryKey: [requestPath, {}],
548
- queryFn: ({ pageParam = requestPath, queryKey }) => new Promise((res, rej) => sendRequest(res, rej, queryKey, pageParam)),
549
- enabled: load && !isFutureQueriesPaused,
550
- getNextPageParam: (lastPage) => constructPaginationLink('next_page', lastPage),
551
- getPreviousPageParam: (lastPage) => constructPaginationLink('previous_page', lastPage),
552
- ...options,
553
- });
554
- const setOptionsAsync = async (fetchOptions) => {
555
- startTransition(() => {
556
- setOptions(fetchOptions);
557
- });
558
- };
559
- const get = async (link, fetchOptions) => {
560
- if (!isFutureQueriesPaused) {
561
- await setOptionsAsync(fetchOptions);
562
- await updatedPathAsync(link);
563
- return query.data;
564
- }
565
- else {
566
- setRequestPayload({ link, fetchOptions });
567
- return undefined;
568
- }
569
- };
570
- useEffect(() => {
571
- if (!isFutureQueriesPaused && requestPayload) {
572
- get(requestPayload.link, requestPayload.fetchOptions);
573
- setRequestPayload(undefined);
574
- }
575
- // eslint-disable-next-line react-hooks/exhaustive-deps
576
- }, [isFutureQueriesPaused]);
577
- const updatedPathAsync = async (link) => {
578
- startTransition(() => {
579
- setRequestPath(link);
580
- });
581
- };
582
- useEffect(() => {
583
- if (keyTracker) {
584
- // set expiration time for the tracker
585
- queryClient.setQueryDefaults([keyTracker], {
586
- staleTime: Infinity,
587
- });
588
- queryClient.setQueryData([keyTracker], [requestPath, {}]);
589
- }
590
- }, [keyTracker, requestPath, queryClient, queryOptions?.staleTime]);
591
- return {
592
- get,
593
- ...query,
594
- isLoading: query.isLoading || isFutureQueriesPaused,
595
- };
495
+ const useGetInfiniteRequest = ({ path, load = false, queryOptions, keyTracker, baseUrl, headers, }) => {
496
+ const { API_URL, TIMEOUT } = useEnvironmentVariables();
497
+ const globalHeaders = useHeaderStore((state) => state.headers);
498
+ const [requestPath, setRequestPath] = useState(path);
499
+ const [options, setOptions] = useState(queryOptions);
500
+ const { options: queryConfigOptions } = useQueryConfig();
501
+ const [requestPayload, setRequestPayload] = useState();
502
+ const isFutureQueriesPaused = usePauseFutureRequests((state) => state.isFutureQueriesPaused);
503
+ let queryClient = useQueryClient();
504
+ // eslint-disable-next-line react-hooks/exhaustive-deps
505
+ queryClient = useMemo(() => queryClient, []);
506
+ const sendRequest = async (res, rej, pageParam) => {
507
+ if (load) {
508
+ // get request headers
509
+ const requestOptions = {
510
+ path: pageParam ?? requestPath,
511
+ headers: { ...globalHeaders, ...headers },
512
+ baseURL: baseUrl ?? API_URL,
513
+ timeout: TIMEOUT,
514
+ };
515
+ let getResponse;
516
+ if (queryConfigOptions?.middleware) {
517
+ // perform global middleware
518
+ getResponse = await queryConfigOptions.middleware(async () => await makeRequest(requestOptions), {
519
+ path,
520
+ baseUrl: baseUrl ?? API_URL,
521
+ });
522
+ }
523
+ else {
524
+ getResponse = await makeRequest(requestOptions);
525
+ }
526
+ if (getResponse.status) {
527
+ res(getResponse);
528
+ }
529
+ else {
530
+ rej(getResponse);
531
+ }
532
+ }
533
+ else {
534
+ rej(null);
535
+ }
536
+ };
537
+ /**
538
+ *
539
+ * This pagination implementation is currently tied to our use case
540
+ */
541
+ const constructPaginationLink = (direction, lastPage) => {
542
+ const [pathname, queryString] = requestPath.split('?');
543
+ const queryParams = new URLSearchParams(queryString);
544
+ const lastPageItem = lastPage.data.pagination[direction];
545
+ queryParams.set('page', String(lastPageItem));
546
+ return pathname + '?' + queryParams.toString();
547
+ };
548
+ const query = useInfiniteQuery({
549
+ queryKey: [requestPath, {}],
550
+ queryFn: ({ pageParam = requestPath }) => new Promise((res, rej) => sendRequest(res, rej, pageParam)),
551
+ enabled: load && !isFutureQueriesPaused,
552
+ getNextPageParam: (lastPage) => constructPaginationLink('next_page', lastPage),
553
+ getPreviousPageParam: (lastPage) => constructPaginationLink('previous_page', lastPage),
554
+ ...options,
555
+ });
556
+ const setOptionsAsync = async (fetchOptions) => {
557
+ startTransition(() => {
558
+ setOptions(fetchOptions);
559
+ });
560
+ };
561
+ const get = async (link, fetchOptions) => {
562
+ if (!isFutureQueriesPaused) {
563
+ await setOptionsAsync(fetchOptions);
564
+ await updatedPathAsync(link);
565
+ return query.data;
566
+ }
567
+ else {
568
+ setRequestPayload({ link, fetchOptions });
569
+ return undefined;
570
+ }
571
+ };
572
+ useEffect(() => {
573
+ if (!isFutureQueriesPaused && requestPayload) {
574
+ get(requestPayload.link, requestPayload.fetchOptions);
575
+ setRequestPayload(undefined);
576
+ }
577
+ // eslint-disable-next-line react-hooks/exhaustive-deps
578
+ }, [isFutureQueriesPaused]);
579
+ const updatedPathAsync = async (link) => {
580
+ startTransition(() => {
581
+ setRequestPath(link);
582
+ });
583
+ };
584
+ useEffect(() => {
585
+ if (keyTracker) {
586
+ // set expiration time for the tracker
587
+ queryClient.setQueryDefaults([keyTracker], {
588
+ staleTime: Infinity,
589
+ });
590
+ queryClient.setQueryData([keyTracker], [requestPath, {}]);
591
+ }
592
+ }, [keyTracker, requestPath, queryClient, queryOptions?.staleTime]);
593
+ return {
594
+ get,
595
+ ...query,
596
+ isLoading: query.isLoading || isFutureQueriesPaused,
597
+ };
596
598
  };
597
599
 
598
- const useGetRequest = ({ path, load = false, queryOptions, keyTracker, baseUrl, headers, }) => {
599
- const [requestPath, setRequestPath] = useState(path);
600
- const [options, setOptions] = useState(queryOptions);
601
- const [page, setPage] = useState(1);
602
- const { API_URL, TIMEOUT } = useEnvironmentVariables();
603
- const globalHeaders = useHeaderStore((state) => state.headers);
604
- const { options: queryConfigOptions } = useQueryConfig();
605
- const [requestPayload, setRequestPayload] = useState();
606
- const isFutureQueriesPaused = usePauseFutureRequests((state) => state.isFutureQueriesPaused);
607
- let queryClient = useQueryClient();
608
- // eslint-disable-next-line react-hooks/exhaustive-deps
609
- queryClient = useMemo(() => queryClient, []);
610
- const sendRequest = async (res, rej, queryKey) => {
611
- if (load) {
612
- const [url] = queryKey;
613
- const requestUrl = (url ?? requestPath);
614
- const requestOptions = {
615
- path: requestUrl,
616
- headers: { ...globalHeaders, ...headers },
617
- baseURL: baseUrl ?? API_URL,
618
- timeout: TIMEOUT,
619
- };
620
- let shouldContinue = true;
621
- if (queryConfigOptions?.queryMiddleware) {
622
- shouldContinue = await queryConfigOptions.queryMiddleware({ queryKey, ...requestOptions });
623
- }
624
- if (shouldContinue) {
625
- const getResponse = await makeRequest(requestOptions);
626
- if (getResponse.status) {
627
- res(getResponse);
628
- }
629
- else {
630
- rej(getResponse);
631
- }
632
- }
633
- else {
634
- rej(null);
635
- }
636
- }
637
- else {
638
- res(null);
639
- }
640
- };
641
- const query = useQuery({
642
- queryKey: [requestPath, {}],
643
- queryFn: ({ queryKey }) => new Promise((res, rej) => sendRequest(res, rej, queryKey)),
644
- enabled: load && !isFutureQueriesPaused,
645
- ...options,
646
- });
647
- useEffect(() => {
648
- if (path) {
649
- setRequestPath(path);
650
- }
651
- }, [path]);
652
- useEffect(() => {
653
- if (keyTracker) {
654
- // set expiration time for the tracker
655
- queryClient.setQueryDefaults([keyTracker], {
656
- staleTime: Infinity,
657
- });
658
- queryClient.setQueryData([keyTracker], [requestPath, {}]);
659
- }
660
- }, [keyTracker, requestPath, queryClient, queryOptions?.staleTime]);
661
- const nextPage = () => {
662
- if (query.data?.data.pagination) {
663
- const pagination = query.data.data.pagination;
664
- if (pagination.next_page !== pagination.current_page && pagination.next_page > pagination.current_page) {
665
- setRequestPath(constructPaginationLink(requestPath, pagination.next_page));
666
- }
667
- }
668
- };
669
- const prevPage = () => {
670
- if (query.data?.data.pagination) {
671
- const pagination = query.data.data.pagination;
672
- if (pagination.previous_page !== pagination.current_page && pagination.previous_page < pagination.current_page) {
673
- setRequestPath(constructPaginationLink(requestPath, pagination.previous_page));
674
- }
675
- }
676
- };
677
- const constructPaginationLink = (link, pageNumber) => {
678
- const [pathname, queryString] = link.split('?');
679
- const queryParams = new URLSearchParams(queryString);
680
- const oldPage = Number(queryParams.get('page'));
681
- queryParams.set('page', pageNumber);
682
- link = pathname + '?' + queryParams.toString();
683
- // only update page when pagination number changed
684
- if (oldPage !== pageNumber) {
685
- setPage(pageNumber);
686
- }
687
- return link;
688
- };
689
- const gotoPage = (pageNumber) => {
690
- setRequestPath(constructPaginationLink(requestPath, pageNumber));
691
- };
692
- const updatedPathAsync = async (link) => {
693
- startTransition(() => {
694
- setRequestPath(link);
695
- });
696
- };
697
- const setOptionsAsync = async (fetchOptions) => {
698
- startTransition(() => {
699
- setOptions(fetchOptions);
700
- });
701
- };
702
- const get = async (link, fetchOptions) => {
703
- if (!isFutureQueriesPaused) {
704
- await setOptionsAsync(fetchOptions);
705
- await updatedPathAsync(link);
706
- return query.data;
707
- }
708
- else {
709
- setRequestPayload({ link, fetchOptions });
710
- return undefined;
711
- }
712
- };
713
- useEffect(() => {
714
- if (!isFutureQueriesPaused && requestPayload) {
715
- get(requestPayload.link, requestPayload.fetchOptions);
716
- setRequestPayload(undefined);
717
- }
718
- // eslint-disable-next-line react-hooks/exhaustive-deps
719
- }, [isFutureQueriesPaused]);
720
- return {
721
- ...query,
722
- isLoading: query.isLoading || isFutureQueriesPaused,
723
- setRequestPath,
724
- nextPage,
725
- prevPage,
726
- get,
727
- gotoPage,
728
- page,
729
- queryKey: [requestPath, {}],
730
- };
600
+ const useGetRequest = ({ path, load = false, queryOptions, keyTracker, baseUrl, headers, }) => {
601
+ const [requestPath, setRequestPath] = useState(path);
602
+ const [options, setOptions] = useState(queryOptions);
603
+ const [page, setPage] = useState(1);
604
+ const { API_URL, TIMEOUT } = useEnvironmentVariables();
605
+ const globalHeaders = useHeaderStore((state) => state.headers);
606
+ const { options: queryConfigOptions } = useQueryConfig();
607
+ const [requestPayload, setRequestPayload] = useState();
608
+ const isFutureQueriesPaused = usePauseFutureRequests((state) => state.isFutureQueriesPaused);
609
+ let queryClient = useQueryClient();
610
+ // eslint-disable-next-line react-hooks/exhaustive-deps
611
+ queryClient = useMemo(() => queryClient, []);
612
+ const sendRequest = async (res, rej, queryKey) => {
613
+ const [url] = queryKey;
614
+ const requestUrl = (url ?? requestPath);
615
+ const requestOptions = {
616
+ path: requestUrl,
617
+ headers: { ...globalHeaders, ...headers },
618
+ baseURL: baseUrl ?? API_URL,
619
+ timeout: TIMEOUT,
620
+ };
621
+ let getResponse;
622
+ if (queryConfigOptions?.middleware) {
623
+ // perform global middleware
624
+ getResponse = await queryConfigOptions.middleware(async () => await makeRequest(requestOptions), {
625
+ path,
626
+ baseUrl: baseUrl ?? API_URL,
627
+ });
628
+ }
629
+ else {
630
+ getResponse = await makeRequest(requestOptions);
631
+ }
632
+ if (getResponse.status) {
633
+ res(getResponse);
634
+ }
635
+ else {
636
+ rej(getResponse);
637
+ }
638
+ };
639
+ const query = useQuery({
640
+ queryKey: [requestPath, {}],
641
+ queryFn: ({ queryKey }) => new Promise((res, rej) => sendRequest(res, rej, queryKey)),
642
+ enabled: load && !isFutureQueriesPaused,
643
+ ...options,
644
+ });
645
+ useEffect(() => {
646
+ if (path) {
647
+ setRequestPath(path);
648
+ }
649
+ }, [path]);
650
+ useEffect(() => {
651
+ if (keyTracker) {
652
+ // set expiration time for the tracker
653
+ queryClient.setQueryDefaults([keyTracker], {
654
+ staleTime: Infinity,
655
+ });
656
+ queryClient.setQueryData([keyTracker], [requestPath, {}]);
657
+ }
658
+ }, [keyTracker, requestPath, queryClient, queryOptions?.staleTime]);
659
+ const nextPage = () => {
660
+ if (query.data.data.pagination) {
661
+ const pagination = query.data.data.pagination;
662
+ if (pagination.next_page !== pagination.current_page && pagination.next_page > pagination.current_page) {
663
+ setRequestPath(constructPaginationLink(requestPath, pagination.next_page));
664
+ }
665
+ }
666
+ };
667
+ const prevPage = () => {
668
+ if (query.data.data.pagination) {
669
+ const pagination = query.data.data.pagination;
670
+ if (pagination.previous_page !== pagination.current_page && pagination.previous_page < pagination.current_page) {
671
+ setRequestPath(constructPaginationLink(requestPath, pagination.previous_page));
672
+ }
673
+ }
674
+ };
675
+ const constructPaginationLink = (link, pageNumber) => {
676
+ const [pathname, queryString] = link.split('?');
677
+ const queryParams = new URLSearchParams(queryString);
678
+ const oldPage = Number(queryParams.get('page'));
679
+ queryParams.set('page', pageNumber);
680
+ link = pathname + '?' + queryParams.toString();
681
+ // only update page when pagination number changed
682
+ if (oldPage !== pageNumber) {
683
+ setPage(pageNumber);
684
+ }
685
+ return link;
686
+ };
687
+ const gotoPage = (pageNumber) => {
688
+ setRequestPath(constructPaginationLink(requestPath, pageNumber));
689
+ };
690
+ const updatedPathAsync = async (link) => {
691
+ startTransition(() => {
692
+ setRequestPath(link);
693
+ });
694
+ };
695
+ const setOptionsAsync = async (fetchOptions) => {
696
+ startTransition(() => {
697
+ setOptions(fetchOptions);
698
+ });
699
+ };
700
+ const get = async (link, fetchOptions) => {
701
+ if (!isFutureQueriesPaused) {
702
+ await setOptionsAsync(fetchOptions);
703
+ await updatedPathAsync(link);
704
+ return query.data;
705
+ }
706
+ else {
707
+ setRequestPayload({ link, fetchOptions });
708
+ return undefined;
709
+ }
710
+ };
711
+ useEffect(() => {
712
+ if (!isFutureQueriesPaused && requestPayload) {
713
+ get(requestPayload.link, requestPayload.fetchOptions);
714
+ setRequestPayload(undefined);
715
+ }
716
+ // eslint-disable-next-line react-hooks/exhaustive-deps
717
+ }, [isFutureQueriesPaused]);
718
+ return {
719
+ ...query,
720
+ isLoading: query.isLoading || isFutureQueriesPaused,
721
+ setRequestPath,
722
+ nextPage,
723
+ prevPage,
724
+ get,
725
+ gotoPage,
726
+ page,
727
+ queryKey: [requestPath, {}],
728
+ };
731
729
  };
732
730
 
733
- const usePatchRequest = ({ path, baseUrl, headers }) => {
734
- const { API_URL, TIMEOUT } = useEnvironmentVariables();
735
- const { uploadProgressPercent, onUploadProgress } = useUploadProgress();
736
- const globalHeaders = useHeaderStore((state) => state.headers);
737
- const [requestPayload, setRequestPayload] = useState();
738
- const isFutureMutationsPaused = usePauseFutureRequests((state) => state.isFutureMutationsPaused);
739
- const config = useQueryConfig();
740
- const sendRequest = async (res, rej, data) => {
741
- // get request headers
742
- const requestOptions = {
743
- path: path,
744
- body: data,
745
- method: HttpMethod.PATCH,
746
- headers: { ...globalHeaders, ...headers },
747
- baseURL: baseUrl ?? API_URL,
748
- timeout: TIMEOUT,
749
- onUploadProgress,
750
- };
751
- let shouldContinue = true;
752
- if (config.options?.mutationMiddleware) {
753
- shouldContinue = await config.options.mutationMiddleware({
754
- mutationKey: [path, { type: 'mutation' }],
755
- ...requestOptions,
756
- });
757
- }
758
- if (shouldContinue) {
759
- const patchResponse = await makeRequest(requestOptions);
760
- if (patchResponse.status) {
761
- // scroll to top after success
762
- if (config.options?.context !== 'app') {
763
- scrollToTop();
764
- }
765
- res(patchResponse);
766
- }
767
- else {
768
- // scroll to top after error
769
- if (config.options?.context !== 'app') {
770
- scrollToTop();
771
- }
772
- rej(patchResponse);
773
- }
774
- }
775
- else {
776
- rej(null);
777
- }
778
- };
779
- // register post mutation
780
- const mutation = useMutation({
781
- mutationKey: [path, { type: 'mutation' }],
782
- mutationFn: (dataData) => new Promise((res, rej) => {
783
- return sendRequest(res, rej, dataData);
784
- }),
785
- });
786
- const patch = async (data, options) => {
787
- if (!isFutureMutationsPaused) {
788
- return mutation.mutateAsync(data, options);
789
- }
790
- else {
791
- setRequestPayload({ data, options });
792
- return undefined;
793
- }
794
- };
795
- useEffect(() => {
796
- if (!isFutureMutationsPaused && requestPayload) {
797
- patch(requestPayload.data, requestPayload.options);
798
- setRequestPayload(undefined);
799
- }
800
- // eslint-disable-next-line react-hooks/exhaustive-deps
801
- }, [isFutureMutationsPaused]);
802
- return { patch, uploadProgressPercent, ...mutation, isLoading: mutation.isPending || isFutureMutationsPaused };
731
+ const usePatchRequest = ({ path, baseUrl, headers }) => {
732
+ const { API_URL, TIMEOUT } = useEnvironmentVariables();
733
+ const { uploadProgressPercent, onUploadProgress } = useUploadProgress();
734
+ const globalHeaders = useHeaderStore((state) => state.headers);
735
+ const [requestPayload, setRequestPayload] = useState();
736
+ const isFutureMutationsPaused = usePauseFutureRequests((state) => state.isFutureMutationsPaused);
737
+ const config = useQueryConfig();
738
+ const sendRequest = async (res, rej, data) => {
739
+ // get request headers
740
+ const requestOptions = {
741
+ path: path,
742
+ body: data,
743
+ method: HttpMethod.PATCH,
744
+ headers: { ...globalHeaders, ...headers },
745
+ baseURL: baseUrl ?? API_URL,
746
+ timeout: TIMEOUT,
747
+ onUploadProgress,
748
+ };
749
+ let patchResponse;
750
+ if (config.options?.middleware) {
751
+ // perform global middleware
752
+ const middlewareResponse = await config.options.middleware(async () => await makeRequest(requestOptions), {
753
+ path,
754
+ baseUrl: baseUrl ?? API_URL,
755
+ body: data,
756
+ });
757
+ patchResponse = middlewareResponse;
758
+ }
759
+ else {
760
+ patchResponse = await makeRequest(requestOptions);
761
+ }
762
+ if (patchResponse.status) {
763
+ // scroll to top after success
764
+ if (config.options?.context !== 'app') {
765
+ scrollToTop();
766
+ }
767
+ res(patchResponse);
768
+ }
769
+ else {
770
+ // scroll to top after error
771
+ if (config.options?.context !== 'app') {
772
+ scrollToTop();
773
+ }
774
+ rej(patchResponse);
775
+ }
776
+ };
777
+ // register post mutation
778
+ const mutation = useMutation({
779
+ mutationKey: [path, { type: 'mutation' }],
780
+ mutationFn: (dataData) => new Promise((res, rej) => {
781
+ return sendRequest(res, rej, dataData);
782
+ }),
783
+ });
784
+ const patch = async (data, options) => {
785
+ if (!isFutureMutationsPaused) {
786
+ return mutation.mutateAsync(data, options);
787
+ }
788
+ else {
789
+ setRequestPayload({ data, options });
790
+ return undefined;
791
+ }
792
+ };
793
+ useEffect(() => {
794
+ if (!isFutureMutationsPaused && requestPayload) {
795
+ patch(requestPayload.data, requestPayload.options);
796
+ setRequestPayload(undefined);
797
+ }
798
+ // eslint-disable-next-line react-hooks/exhaustive-deps
799
+ }, [isFutureMutationsPaused]);
800
+ return { patch, uploadProgressPercent, ...mutation, isLoading: mutation.isPending || isFutureMutationsPaused };
803
801
  };
804
802
 
805
- const usePostRequest = ({ path, isFormData = false, baseUrl, headers, fileSelectors, }) => {
806
- const { API_URL, TIMEOUT } = useEnvironmentVariables();
807
- const config = useQueryConfig();
808
- const globalHeaders = useHeaderStore((state) => state.headers);
809
- const { isApp } = useReactNativeEnv();
810
- const { uploadProgressPercent, onUploadProgress } = useUploadProgress();
811
- const [requestPayload, setRequestPayload] = useState();
812
- const isFutureMutationsPaused = usePauseFutureRequests((state) => state.isFutureMutationsPaused);
813
- const sendRequest = async (res, rej, postData) => {
814
- // get request headers
815
- const { data, requestConfig } = postData;
816
- delete requestConfig?.body;
817
- const requestOptions = {
818
- path,
819
- body: data,
820
- method: HttpMethod.POST,
821
- isFormData,
822
- headers: { ...globalHeaders, ...headers },
823
- baseURL: baseUrl ?? API_URL,
824
- timeout: TIMEOUT,
825
- appFileConfig: {
826
- isApp,
827
- fileSelectors,
828
- },
829
- onUploadProgress,
830
- ...requestConfig,
831
- };
832
- let shouldContinue = true;
833
- if (config.options?.mutationMiddleware) {
834
- shouldContinue = await config.options.mutationMiddleware({
835
- mutationKey: [path, { type: 'mutation' }],
836
- ...requestOptions,
837
- });
838
- }
839
- if (shouldContinue) {
840
- const postResponse = await makeRequest(requestOptions);
841
- if (postResponse.status) {
842
- // scroll to top after success
843
- if (config.options?.context !== 'app') {
844
- scrollToTop();
845
- }
846
- res(postResponse);
847
- }
848
- else {
849
- // scroll to top after error
850
- if (config.options?.context !== 'app') {
851
- scrollToTop();
852
- }
853
- rej(postResponse);
854
- }
855
- }
856
- else {
857
- rej(null);
858
- }
859
- };
860
- // register post mutation
861
- const mutation = useMutation({
862
- mutationKey: [path, { type: 'mutation' }],
863
- mutationFn: async (postData) => new Promise((res, rej) => sendRequest(res, rej, postData)),
864
- });
865
- const post = async (data, options) => {
866
- if (!isFutureMutationsPaused) {
867
- const { requestConfig, ...otherOptions } = options ?? {};
868
- return mutation.mutateAsync({ data, requestConfig }, otherOptions);
869
- }
870
- else {
871
- setRequestPayload({ data, options });
872
- return undefined;
873
- }
874
- };
875
- useEffect(() => {
876
- if (!isFutureMutationsPaused && requestPayload) {
877
- post(requestPayload.data, requestPayload.options);
878
- setRequestPayload(undefined);
879
- }
880
- // eslint-disable-next-line react-hooks/exhaustive-deps
881
- }, [isFutureMutationsPaused]);
882
- return { post, uploadProgressPercent, ...mutation, isLoading: mutation.isPending || isFutureMutationsPaused };
803
+ const usePostRequest = ({ path, isFormData = false, baseUrl, headers, fileSelectors, }) => {
804
+ const { API_URL, TIMEOUT } = useEnvironmentVariables();
805
+ const config = useQueryConfig();
806
+ const globalHeaders = useHeaderStore((state) => state.headers);
807
+ const { isApp } = useReactNativeEnv();
808
+ const { uploadProgressPercent, onUploadProgress } = useUploadProgress();
809
+ const [requestPayload, setRequestPayload] = useState();
810
+ const isFutureMutationsPaused = usePauseFutureRequests((state) => state.isFutureMutationsPaused);
811
+ const sendRequest = async (res, rej, postData) => {
812
+ // get request headers
813
+ const { data, requestConfig } = postData;
814
+ delete requestConfig?.body;
815
+ const requestOptions = {
816
+ path,
817
+ body: data,
818
+ method: HttpMethod.POST,
819
+ isFormData,
820
+ headers: { ...globalHeaders, ...headers },
821
+ baseURL: baseUrl ?? API_URL,
822
+ timeout: TIMEOUT,
823
+ appFileConfig: {
824
+ isApp,
825
+ fileSelectors,
826
+ },
827
+ onUploadProgress,
828
+ ...requestConfig,
829
+ };
830
+ let postResponse;
831
+ if (config.options?.middleware) {
832
+ // perform global middleware
833
+ postResponse = await config.options.middleware(async () => await makeRequest(requestOptions), {
834
+ path,
835
+ baseUrl: baseUrl ?? API_URL,
836
+ body: data,
837
+ });
838
+ }
839
+ else {
840
+ postResponse = await makeRequest(requestOptions);
841
+ }
842
+ if (postResponse.status) {
843
+ // scroll to top after success
844
+ if (config.options?.context !== 'app') {
845
+ scrollToTop();
846
+ }
847
+ res(postResponse);
848
+ }
849
+ else {
850
+ // scroll to top after error
851
+ if (config.options?.context !== 'app') {
852
+ scrollToTop();
853
+ }
854
+ rej(postResponse);
855
+ }
856
+ };
857
+ // register post mutation
858
+ const mutation = useMutation({
859
+ mutationKey: [path, { type: 'mutation' }],
860
+ mutationFn: async (postData) => new Promise((res, rej) => sendRequest(res, rej, postData)),
861
+ });
862
+ const post = async (data, options) => {
863
+ if (!isFutureMutationsPaused) {
864
+ const { requestConfig, ...otherOptions } = options ?? {};
865
+ return mutation.mutateAsync({ data, requestConfig }, otherOptions);
866
+ }
867
+ else {
868
+ setRequestPayload({ data, options });
869
+ return undefined;
870
+ }
871
+ };
872
+ useEffect(() => {
873
+ if (!isFutureMutationsPaused && requestPayload) {
874
+ post(requestPayload.data, requestPayload.options);
875
+ setRequestPayload(undefined);
876
+ }
877
+ // eslint-disable-next-line react-hooks/exhaustive-deps
878
+ }, [isFutureMutationsPaused]);
879
+ return { post, uploadProgressPercent, ...mutation, isLoading: mutation.isPending || isFutureMutationsPaused };
883
880
  };
884
881
 
885
882
  export { ContentType, HttpMethod, axiosInstance, bootstrapQueryRequest, buildFormData, errorTransformer, getDateInFuture, makeRequest, scrollToTop, successTransformer, useDeleteRequest, useEnvironmentVariables, useGetInfiniteRequest, useGetRequest, useHeaderStore, useKeyTrackerModel, usePatchRequest, usePauseFutureRequests, usePostRequest, useQueryConfig, useQueryHeaders, useQueryModel, useReactNativeEnv, useRefetchQuery, useUploadProgress };