@leancodepl/react-query-cqrs-client 8.4.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@leancodepl/react-query-cqrs-client",
3
- "version": "8.4.0",
3
+ "version": "8.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "dependencies": {
6
- "@leancodepl/cqrs-client-base": "8.4.0",
7
- "@leancodepl/utils": "8.4.0",
8
- "@leancodepl/validation": "8.4.0",
6
+ "@leancodepl/cqrs-client-base": "8.5.0",
7
+ "@leancodepl/utils": "8.5.0",
8
+ "@leancodepl/validation": "8.5.0",
9
9
  "@tanstack/react-query": ">=5.0.0",
10
10
  "rxjs": ">=7.0.0"
11
11
  },
@@ -13,16 +13,53 @@
13
13
  "@testing-library/react": "*",
14
14
  "react": "*"
15
15
  },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "registry": "https://registry.npmjs.org/"
19
+ },
20
+ "engines": {
21
+ "node": ">=18.0.0"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/leancodepl/js_corelibrary.git",
26
+ "directory": "packages/cqrs-clients/react-query-cqrs-client"
27
+ },
28
+ "homepage": "https://github.com/leancodepl/js_corelibrary",
29
+ "bugs": {
30
+ "url": "https://github.com/leancodepl/js_corelibrary/issues"
31
+ },
32
+ "description": "TanStack Query integration for CQRS commands and queries",
33
+ "keywords": [
34
+ "cqrs",
35
+ "tanstack-query",
36
+ "react",
37
+ "hooks",
38
+ "cache",
39
+ "typescript",
40
+ "javascript",
41
+ "leancode"
42
+ ],
43
+ "author": {
44
+ "name": "LeanCode",
45
+ "url": "https://leancode.co"
46
+ },
47
+ "files": [
48
+ "dist",
49
+ "README.md",
50
+ "CHANGELOG.md"
51
+ ],
52
+ "sideEffects": false,
16
53
  "exports": {
17
54
  "./package.json": "./package.json",
18
55
  ".": {
19
56
  "module": "./index.esm.js",
20
- "types": "./index.esm.d.ts",
57
+ "types": "./index.d.ts",
21
58
  "import": "./index.cjs.mjs",
22
59
  "default": "./index.cjs.js"
23
60
  }
24
61
  },
25
62
  "module": "./index.esm.js",
26
63
  "main": "./index.cjs.js",
27
- "types": "./index.esm.d.ts"
64
+ "types": "./index.d.ts"
28
65
  }
package/index.cjs.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/index";
@@ -1 +0,0 @@
1
- exports._default = require('./index.cjs.js').default;
package/index.cjs.js DELETED
@@ -1,261 +0,0 @@
1
- 'use strict';
2
-
3
- var reactQuery = require('@tanstack/react-query');
4
- var rxjs = require('rxjs');
5
- var ajax = require('rxjs/ajax');
6
- var operators = require('rxjs/operators');
7
- var validation = require('@leancodepl/validation');
8
- var utils = require('@leancodepl/utils');
9
-
10
- function _extends() {
11
- _extends = Object.assign || function assign(target) {
12
- for(var i = 1; i < arguments.length; i++){
13
- var source = arguments[i];
14
- for(var key in source)if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
15
- }
16
- return target;
17
- };
18
- return _extends.apply(this, arguments);
19
- }
20
-
21
- function _object_without_properties_loose(source, excluded) {
22
- if (source == null) return {};
23
- var target = {};
24
- var sourceKeys = Object.keys(source);
25
- var key, i;
26
- for(i = 0; i < sourceKeys.length; i++){
27
- key = sourceKeys[i];
28
- if (excluded.indexOf(key) >= 0) continue;
29
- target[key] = source[key];
30
- }
31
- return target;
32
- }
33
-
34
- function authGuard(tokenProvider) {
35
- if (!(tokenProvider == null ? void 0 : tokenProvider.invalidateToken)) {
36
- return (response)=>response;
37
- }
38
- return (response)=>response.pipe(rxjs.catchError((error)=>{
39
- if (error.status === 401) {
40
- tokenProvider.invalidateToken == null ? void 0 : tokenProvider.invalidateToken.call(tokenProvider);
41
- }
42
- return rxjs.throwError(()=>error);
43
- }));
44
- }
45
-
46
- function uncapitalizedJSONParse(json) {
47
- return JSON.parse(json, (key, value)=>{
48
- if (value === null && key !== "") return undefined;
49
- if (!value || Array.isArray(value) || typeof value !== "object") return value;
50
- return Object.fromEntries(Object.entries(value).map(([key, value])=>[
51
- utils.toLowerFirst(key),
52
- value
53
- ]));
54
- });
55
- }
56
-
57
- function uncapitalizedParse() {
58
- return ($source)=>$source.pipe(operators.map(uncapitalizedJSONParse));
59
- }
60
- function mkCqrsClient({ cqrsEndpoint, queryClient, tokenProvider, ajaxOptions, tokenHeader = "Authorization" }) {
61
- function mkFetcher(endpoint, config = {}) {
62
- const apiCall = (data, token)=>{
63
- var _ajaxOptions_withCredentials;
64
- return ajax.ajax(_extends({}, ajaxOptions, config, {
65
- headers: {
66
- [tokenHeader]: token,
67
- "Content-Type": "application/json"
68
- },
69
- url: `${cqrsEndpoint}/${endpoint}`,
70
- method: "POST",
71
- body: data,
72
- withCredentials: (_ajaxOptions_withCredentials = ajaxOptions == null ? void 0 : ajaxOptions.withCredentials) != null ? _ajaxOptions_withCredentials : true
73
- }));
74
- };
75
- const getToken = tokenProvider == null ? void 0 : tokenProvider.getToken;
76
- const mk$apiCall = (data, token)=>apiCall(data, token).pipe(authGuard(tokenProvider), operators.map((result)=>result.response));
77
- if (getToken) {
78
- return (data)=>rxjs.from(getToken()).pipe(operators.mergeMap((token)=>mk$apiCall(data, token)));
79
- }
80
- return (data)=>mk$apiCall(data);
81
- }
82
- return {
83
- createQuery (type) {
84
- const fetcher = mkFetcher(`query/${type}`, {
85
- responseType: "text"
86
- });
87
- function useApiQuery(data, options) {
88
- return reactQuery.useQuery(_extends({
89
- queryKey: useApiQuery.key(data),
90
- queryFn: (context)=>rxjs.firstValueFrom(useApiQuery.fetcher(data, context))
91
- }, options), queryClient);
92
- }
93
- useApiQuery.type = type;
94
- useApiQuery.fetcher = (data, context)=>rxjs.race([
95
- fetcher(data).pipe(uncapitalizedParse()),
96
- ...(context == null ? void 0 : context.signal) ? [
97
- rxjs.fromEvent(context.signal, "abort").pipe(operators.mergeMap(()=>rxjs.throwError(()=>new Error("Query aborted"))))
98
- ] : []
99
- ]);
100
- useApiQuery.fetch = (data, options)=>queryClient.fetchQuery(_extends({
101
- queryKey: useApiQuery.key(data),
102
- queryFn: (context)=>rxjs.firstValueFrom(useApiQuery.fetcher(data, context))
103
- }, options));
104
- useApiQuery.lazy = function(options = {}) {
105
- // eslint-disable-next-line react-hooks/rules-of-hooks
106
- return reactQuery.useMutation(_extends({
107
- mutationKey: [
108
- type
109
- ],
110
- mutationFn: (variables)=>rxjs.firstValueFrom(useApiQuery.fetcher(variables))
111
- }, options), queryClient);
112
- };
113
- useApiQuery.infinite = function(initialPageData, options) {
114
- // eslint-disable-next-line react-hooks/rules-of-hooks
115
- return reactQuery.useInfiniteQuery(_extends({
116
- queryKey: [
117
- type
118
- ],
119
- queryFn: async (context)=>await rxjs.firstValueFrom(useApiQuery.fetcher(context.pageParam, context)),
120
- initialPageParam: initialPageData
121
- }, options), queryClient);
122
- };
123
- useApiQuery.key = (query)=>[
124
- type,
125
- query
126
- ];
127
- function setQueryData(queryOrQueryKey, updater) {
128
- const key = Array.isArray(queryOrQueryKey) ? queryOrQueryKey : useApiQuery.key(queryOrQueryKey);
129
- return queryClient.setQueryData(key, updater);
130
- }
131
- useApiQuery.setQueryData = setQueryData;
132
- useApiQuery.setQueriesData = (query, updater)=>queryClient.setQueriesData({
133
- queryKey: useApiQuery.key(query)
134
- }, updater);
135
- useApiQuery.getQueryData = (query)=>queryClient.getQueryData(useApiQuery.key(query));
136
- useApiQuery.getQueriesData = (query)=>queryClient.getQueriesData({
137
- queryKey: useApiQuery.key(query)
138
- });
139
- useApiQuery.prefetch = (data, options)=>queryClient.prefetchQuery(_extends({
140
- queryKey: useApiQuery.key(data),
141
- queryFn: (context)=>rxjs.firstValueFrom(useApiQuery.fetcher(data, context))
142
- }, options));
143
- useApiQuery.invalidate = (query)=>queryClient.invalidateQueries({
144
- queryKey: useApiQuery.key(query)
145
- });
146
- useApiQuery.cancel = (query)=>queryClient.cancelQueries({
147
- queryKey: useApiQuery.key(query)
148
- });
149
- useApiQuery.optimisticUpdate = async (updater, query = {})=>{
150
- await useApiQuery.cancel(query);
151
- const data = useApiQuery.getQueriesData(query);
152
- useApiQuery.setQueriesData(query, updater);
153
- return ()=>data.forEach(([key, result])=>queryClient.setQueryData(key, result));
154
- };
155
- return useApiQuery;
156
- },
157
- createOperation (type) {
158
- const fetcher = mkFetcher(`operation/${type}`, {
159
- responseType: "text"
160
- });
161
- function useApiOperation(_param = {}) {
162
- var { onSuccess: onSuccessBase, invalidateQueries } = _param, options = _object_without_properties_loose(_param, [
163
- "onSuccess",
164
- "invalidateQueries"
165
- ]);
166
- return reactQuery.useMutation(_extends({
167
- mutationKey: useApiOperation.key,
168
- mutationFn: (variables)=>rxjs.firstValueFrom(useApiOperation.fetcher(variables))
169
- }, options, {
170
- async onSuccess (data, variables, context) {
171
- const result = await (onSuccessBase == null ? void 0 : onSuccessBase(data, variables, context));
172
- if (invalidateQueries) {
173
- await Promise.allSettled(invalidateQueries.map((queryKey)=>queryClient.invalidateQueries({
174
- queryKey
175
- })));
176
- }
177
- return result;
178
- }
179
- }), queryClient);
180
- }
181
- useApiOperation.type = type;
182
- useApiOperation.key = [
183
- useApiOperation.type
184
- ];
185
- useApiOperation.fetcher = (variables)=>fetcher(variables).pipe(uncapitalizedParse());
186
- return useApiOperation;
187
- },
188
- createCommand (type, errorCodes) {
189
- const fetcher = mkFetcher(`command/${type}`);
190
- function useApiCommand(_param = {}) {
191
- var { invalidateQueries, handler, optimisticUpdate, onMutate, onError, onSettled } = _param, options = _object_without_properties_loose(_param, [
192
- "invalidateQueries",
193
- "handler",
194
- "optimisticUpdate",
195
- "onMutate",
196
- "onError",
197
- "onSettled"
198
- ]);
199
- return reactQuery.useMutation(_extends({}, options, {
200
- mutationKey: useApiCommand.key,
201
- mutationFn: (variables)=>rxjs.firstValueFrom(useApiCommand.call(variables, handler)),
202
- async onMutate (variables) {
203
- // there's really no good way to do it without type cast
204
- const baseContext = await (onMutate == null ? void 0 : onMutate(variables));
205
- var _optimisticUpdate;
206
- const optimisticUpdateReverts = await Promise.all((_optimisticUpdate = optimisticUpdate == null ? void 0 : optimisticUpdate(variables)) != null ? _optimisticUpdate : []);
207
- return _extends({}, baseContext, {
208
- revertOptimisticUpdate: ()=>optimisticUpdateReverts.forEach((revertOptimisticUpdate)=>revertOptimisticUpdate())
209
- });
210
- },
211
- async onError (error, variables, context) {
212
- await (onError == null ? void 0 : onError(error, variables, context));
213
- context == null ? void 0 : context.revertOptimisticUpdate();
214
- },
215
- async onSettled (data, error, variables, context) {
216
- if (invalidateQueries) {
217
- await Promise.allSettled(invalidateQueries.map((queryKey)=>queryClient.invalidateQueries({
218
- queryKey
219
- })));
220
- }
221
- return await (onSettled == null ? void 0 : onSettled(data, error, variables, context));
222
- }
223
- }), queryClient);
224
- }
225
- useApiCommand.type = type;
226
- useApiCommand.key = [
227
- useApiCommand.type
228
- ];
229
- useApiCommand.fetcher = (variables)=>fetcher(variables);
230
- useApiCommand.call = (variables, handler)=>{
231
- const $response = useApiCommand.fetcher(variables);
232
- return $response.pipe(operators.map((result)=>({
233
- isSuccess: true,
234
- result
235
- })), rxjs.catchError((e)=>rxjs.of(useApiCommand.mapError(e))), operators.map((response)=>{
236
- const result = handler ? useApiCommand.handleResponse(handler)(response) : response;
237
- if (!response.isSuccess || !response.result.WasSuccessful) {
238
- throw result;
239
- }
240
- return result;
241
- }));
242
- };
243
- useApiCommand.mapError = (e)=>{
244
- if (e instanceof ajax.AjaxError && e.status === 422) {
245
- return {
246
- isSuccess: true,
247
- result: e.response
248
- };
249
- }
250
- return {
251
- isSuccess: false,
252
- error: e
253
- };
254
- };
255
- useApiCommand.handleResponse = (handler)=>(response)=>handler(validation.handleResponse(response, errorCodes));
256
- return useApiCommand;
257
- }
258
- };
259
- }
260
-
261
- exports.mkCqrsClient = mkCqrsClient;
package/index.cjs.mjs DELETED
@@ -1,2 +0,0 @@
1
- export * from './index.cjs.js';
2
- export { _default as default } from './index.cjs.default.js';
package/index.esm.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/index";
package/index.esm.js DELETED
@@ -1,259 +0,0 @@
1
- import { useMutation, useInfiniteQuery, useQuery } from '@tanstack/react-query';
2
- import { catchError, throwError, of, race, fromEvent, from, firstValueFrom } from 'rxjs';
3
- import { AjaxError, ajax } from 'rxjs/ajax';
4
- import { map, mergeMap } from 'rxjs/operators';
5
- import { handleResponse } from '@leancodepl/validation';
6
- import { toLowerFirst } from '@leancodepl/utils';
7
-
8
- function _extends() {
9
- _extends = Object.assign || function assign(target) {
10
- for(var i = 1; i < arguments.length; i++){
11
- var source = arguments[i];
12
- for(var key in source)if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
13
- }
14
- return target;
15
- };
16
- return _extends.apply(this, arguments);
17
- }
18
-
19
- function _object_without_properties_loose(source, excluded) {
20
- if (source == null) return {};
21
- var target = {};
22
- var sourceKeys = Object.keys(source);
23
- var key, i;
24
- for(i = 0; i < sourceKeys.length; i++){
25
- key = sourceKeys[i];
26
- if (excluded.indexOf(key) >= 0) continue;
27
- target[key] = source[key];
28
- }
29
- return target;
30
- }
31
-
32
- function authGuard(tokenProvider) {
33
- if (!(tokenProvider == null ? void 0 : tokenProvider.invalidateToken)) {
34
- return (response)=>response;
35
- }
36
- return (response)=>response.pipe(catchError((error)=>{
37
- if (error.status === 401) {
38
- tokenProvider.invalidateToken == null ? void 0 : tokenProvider.invalidateToken.call(tokenProvider);
39
- }
40
- return throwError(()=>error);
41
- }));
42
- }
43
-
44
- function uncapitalizedJSONParse(json) {
45
- return JSON.parse(json, (key, value)=>{
46
- if (value === null && key !== "") return undefined;
47
- if (!value || Array.isArray(value) || typeof value !== "object") return value;
48
- return Object.fromEntries(Object.entries(value).map(([key, value])=>[
49
- toLowerFirst(key),
50
- value
51
- ]));
52
- });
53
- }
54
-
55
- function uncapitalizedParse() {
56
- return ($source)=>$source.pipe(map(uncapitalizedJSONParse));
57
- }
58
- function mkCqrsClient({ cqrsEndpoint, queryClient, tokenProvider, ajaxOptions, tokenHeader = "Authorization" }) {
59
- function mkFetcher(endpoint, config = {}) {
60
- const apiCall = (data, token)=>{
61
- var _ajaxOptions_withCredentials;
62
- return ajax(_extends({}, ajaxOptions, config, {
63
- headers: {
64
- [tokenHeader]: token,
65
- "Content-Type": "application/json"
66
- },
67
- url: `${cqrsEndpoint}/${endpoint}`,
68
- method: "POST",
69
- body: data,
70
- withCredentials: (_ajaxOptions_withCredentials = ajaxOptions == null ? void 0 : ajaxOptions.withCredentials) != null ? _ajaxOptions_withCredentials : true
71
- }));
72
- };
73
- const getToken = tokenProvider == null ? void 0 : tokenProvider.getToken;
74
- const mk$apiCall = (data, token)=>apiCall(data, token).pipe(authGuard(tokenProvider), map((result)=>result.response));
75
- if (getToken) {
76
- return (data)=>from(getToken()).pipe(mergeMap((token)=>mk$apiCall(data, token)));
77
- }
78
- return (data)=>mk$apiCall(data);
79
- }
80
- return {
81
- createQuery (type) {
82
- const fetcher = mkFetcher(`query/${type}`, {
83
- responseType: "text"
84
- });
85
- function useApiQuery(data, options) {
86
- return useQuery(_extends({
87
- queryKey: useApiQuery.key(data),
88
- queryFn: (context)=>firstValueFrom(useApiQuery.fetcher(data, context))
89
- }, options), queryClient);
90
- }
91
- useApiQuery.type = type;
92
- useApiQuery.fetcher = (data, context)=>race([
93
- fetcher(data).pipe(uncapitalizedParse()),
94
- ...(context == null ? void 0 : context.signal) ? [
95
- fromEvent(context.signal, "abort").pipe(mergeMap(()=>throwError(()=>new Error("Query aborted"))))
96
- ] : []
97
- ]);
98
- useApiQuery.fetch = (data, options)=>queryClient.fetchQuery(_extends({
99
- queryKey: useApiQuery.key(data),
100
- queryFn: (context)=>firstValueFrom(useApiQuery.fetcher(data, context))
101
- }, options));
102
- useApiQuery.lazy = function(options = {}) {
103
- // eslint-disable-next-line react-hooks/rules-of-hooks
104
- return useMutation(_extends({
105
- mutationKey: [
106
- type
107
- ],
108
- mutationFn: (variables)=>firstValueFrom(useApiQuery.fetcher(variables))
109
- }, options), queryClient);
110
- };
111
- useApiQuery.infinite = function(initialPageData, options) {
112
- // eslint-disable-next-line react-hooks/rules-of-hooks
113
- return useInfiniteQuery(_extends({
114
- queryKey: [
115
- type
116
- ],
117
- queryFn: async (context)=>await firstValueFrom(useApiQuery.fetcher(context.pageParam, context)),
118
- initialPageParam: initialPageData
119
- }, options), queryClient);
120
- };
121
- useApiQuery.key = (query)=>[
122
- type,
123
- query
124
- ];
125
- function setQueryData(queryOrQueryKey, updater) {
126
- const key = Array.isArray(queryOrQueryKey) ? queryOrQueryKey : useApiQuery.key(queryOrQueryKey);
127
- return queryClient.setQueryData(key, updater);
128
- }
129
- useApiQuery.setQueryData = setQueryData;
130
- useApiQuery.setQueriesData = (query, updater)=>queryClient.setQueriesData({
131
- queryKey: useApiQuery.key(query)
132
- }, updater);
133
- useApiQuery.getQueryData = (query)=>queryClient.getQueryData(useApiQuery.key(query));
134
- useApiQuery.getQueriesData = (query)=>queryClient.getQueriesData({
135
- queryKey: useApiQuery.key(query)
136
- });
137
- useApiQuery.prefetch = (data, options)=>queryClient.prefetchQuery(_extends({
138
- queryKey: useApiQuery.key(data),
139
- queryFn: (context)=>firstValueFrom(useApiQuery.fetcher(data, context))
140
- }, options));
141
- useApiQuery.invalidate = (query)=>queryClient.invalidateQueries({
142
- queryKey: useApiQuery.key(query)
143
- });
144
- useApiQuery.cancel = (query)=>queryClient.cancelQueries({
145
- queryKey: useApiQuery.key(query)
146
- });
147
- useApiQuery.optimisticUpdate = async (updater, query = {})=>{
148
- await useApiQuery.cancel(query);
149
- const data = useApiQuery.getQueriesData(query);
150
- useApiQuery.setQueriesData(query, updater);
151
- return ()=>data.forEach(([key, result])=>queryClient.setQueryData(key, result));
152
- };
153
- return useApiQuery;
154
- },
155
- createOperation (type) {
156
- const fetcher = mkFetcher(`operation/${type}`, {
157
- responseType: "text"
158
- });
159
- function useApiOperation(_param = {}) {
160
- var { onSuccess: onSuccessBase, invalidateQueries } = _param, options = _object_without_properties_loose(_param, [
161
- "onSuccess",
162
- "invalidateQueries"
163
- ]);
164
- return useMutation(_extends({
165
- mutationKey: useApiOperation.key,
166
- mutationFn: (variables)=>firstValueFrom(useApiOperation.fetcher(variables))
167
- }, options, {
168
- async onSuccess (data, variables, context) {
169
- const result = await (onSuccessBase == null ? void 0 : onSuccessBase(data, variables, context));
170
- if (invalidateQueries) {
171
- await Promise.allSettled(invalidateQueries.map((queryKey)=>queryClient.invalidateQueries({
172
- queryKey
173
- })));
174
- }
175
- return result;
176
- }
177
- }), queryClient);
178
- }
179
- useApiOperation.type = type;
180
- useApiOperation.key = [
181
- useApiOperation.type
182
- ];
183
- useApiOperation.fetcher = (variables)=>fetcher(variables).pipe(uncapitalizedParse());
184
- return useApiOperation;
185
- },
186
- createCommand (type, errorCodes) {
187
- const fetcher = mkFetcher(`command/${type}`);
188
- function useApiCommand(_param = {}) {
189
- var { invalidateQueries, handler, optimisticUpdate, onMutate, onError, onSettled } = _param, options = _object_without_properties_loose(_param, [
190
- "invalidateQueries",
191
- "handler",
192
- "optimisticUpdate",
193
- "onMutate",
194
- "onError",
195
- "onSettled"
196
- ]);
197
- return useMutation(_extends({}, options, {
198
- mutationKey: useApiCommand.key,
199
- mutationFn: (variables)=>firstValueFrom(useApiCommand.call(variables, handler)),
200
- async onMutate (variables) {
201
- // there's really no good way to do it without type cast
202
- const baseContext = await (onMutate == null ? void 0 : onMutate(variables));
203
- var _optimisticUpdate;
204
- const optimisticUpdateReverts = await Promise.all((_optimisticUpdate = optimisticUpdate == null ? void 0 : optimisticUpdate(variables)) != null ? _optimisticUpdate : []);
205
- return _extends({}, baseContext, {
206
- revertOptimisticUpdate: ()=>optimisticUpdateReverts.forEach((revertOptimisticUpdate)=>revertOptimisticUpdate())
207
- });
208
- },
209
- async onError (error, variables, context) {
210
- await (onError == null ? void 0 : onError(error, variables, context));
211
- context == null ? void 0 : context.revertOptimisticUpdate();
212
- },
213
- async onSettled (data, error, variables, context) {
214
- if (invalidateQueries) {
215
- await Promise.allSettled(invalidateQueries.map((queryKey)=>queryClient.invalidateQueries({
216
- queryKey
217
- })));
218
- }
219
- return await (onSettled == null ? void 0 : onSettled(data, error, variables, context));
220
- }
221
- }), queryClient);
222
- }
223
- useApiCommand.type = type;
224
- useApiCommand.key = [
225
- useApiCommand.type
226
- ];
227
- useApiCommand.fetcher = (variables)=>fetcher(variables);
228
- useApiCommand.call = (variables, handler)=>{
229
- const $response = useApiCommand.fetcher(variables);
230
- return $response.pipe(map((result)=>({
231
- isSuccess: true,
232
- result
233
- })), catchError((e)=>of(useApiCommand.mapError(e))), map((response)=>{
234
- const result = handler ? useApiCommand.handleResponse(handler)(response) : response;
235
- if (!response.isSuccess || !response.result.WasSuccessful) {
236
- throw result;
237
- }
238
- return result;
239
- }));
240
- };
241
- useApiCommand.mapError = (e)=>{
242
- if (e instanceof AjaxError && e.status === 422) {
243
- return {
244
- isSuccess: true,
245
- result: e.response
246
- };
247
- }
248
- return {
249
- isSuccess: false,
250
- error: e
251
- };
252
- };
253
- useApiCommand.handleResponse = (handler)=>(response)=>handler(handleResponse(response, errorCodes));
254
- return useApiCommand;
255
- }
256
- };
257
- }
258
-
259
- export { mkCqrsClient };
package/src/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export { mkCqrsClient } from "./lib/mkCqrsClient";
@@ -1,3 +0,0 @@
1
- import { MonoTypeOperatorFunction } from "rxjs";
2
- import { TokenProvider } from "@leancodepl/cqrs-client-base";
3
- export declare function authGuard<T>(tokenProvider?: Partial<TokenProvider>): MonoTypeOperatorFunction<T>;
@@ -1,72 +0,0 @@
1
- import { FetchQueryOptions, InfiniteData, QueryClient, QueryFunctionContext, QueryKey, UndefinedInitialDataInfiniteOptions, UndefinedInitialDataOptions, Updater, UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
2
- import { Observable, OperatorFunction } from "rxjs";
3
- import { AjaxConfig } from "rxjs/ajax";
4
- import { ApiResponse, ApiSuccess, CommandResult, FailedCommandResult, SuccessfulCommandResult, TokenProvider } from "@leancodepl/cqrs-client-base";
5
- import { ValidationErrorsHandler } from "@leancodepl/validation";
6
- import { NullableUncapitalizeDeep } from "./types";
7
- export declare function uncapitalizedParse<TResult>(): OperatorFunction<string, NullableUncapitalizeDeep<TResult>>;
8
- export declare function mkCqrsClient({ cqrsEndpoint, queryClient, tokenProvider, ajaxOptions, tokenHeader, }: {
9
- cqrsEndpoint: string;
10
- queryClient: QueryClient;
11
- tokenProvider?: Partial<TokenProvider>;
12
- ajaxOptions?: Omit<AjaxConfig, "body" | "headers" | "method" | "responseType" | "url">;
13
- tokenHeader?: string;
14
- }): {
15
- createQuery<TQuery, TResult>(type: string): {
16
- (data: TQuery, options?: Omit<UndefinedInitialDataOptions<NullableUncapitalizeDeep<TResult>, unknown>, "queryFn" | "queryKey">): import("@tanstack/react-query").UseQueryResult<NullableUncapitalizeDeep<TResult>, unknown>;
17
- type: string;
18
- fetcher(data: TQuery, context?: QueryFunctionContext<QueryKey>): Observable<NullableUncapitalizeDeep<TResult>>;
19
- fetch(data: TQuery, options?: Omit<FetchQueryOptions<NullableUncapitalizeDeep<TResult>, unknown>, "queryFn" | "queryKey">): Promise<NullableUncapitalizeDeep<TResult>>;
20
- lazy<TContext = unknown>(options?: Omit<UseMutationOptions<NullableUncapitalizeDeep<TResult>, unknown, TQuery, TContext>, "mutationFn" | "mutationKey">): UseMutationResult<NullableUncapitalizeDeep<TResult>, unknown, TQuery, TContext>;
21
- infinite(initialPageData: TQuery, options: Omit<UndefinedInitialDataInfiniteOptions<NullableUncapitalizeDeep<TResult>, unknown, InfiniteData<NullableUncapitalizeDeep<TResult>>, QueryKey, TQuery>, "initialPageParam" | "queryFn" | "queryKey" | "select">): import("@tanstack/react-query").UseInfiniteQueryResult<InfiniteData<NullableUncapitalizeDeep<TResult>, TQuery>, unknown>;
22
- key(query: Partial<TQuery>): readonly [string, Partial<TQuery>];
23
- setQueryData: {
24
- (query: TQuery, updater: Updater<NullableUncapitalizeDeep<TResult> | undefined, NullableUncapitalizeDeep<TResult> | undefined>): NullableUncapitalizeDeep<TResult> | undefined;
25
- (queryKey: QueryKey, updater: Updater<NullableUncapitalizeDeep<TResult> | undefined, NullableUncapitalizeDeep<TResult> | undefined>): NullableUncapitalizeDeep<TResult> | undefined;
26
- };
27
- setQueriesData(query: Partial<TQuery>, updater: Updater<NullableUncapitalizeDeep<TResult> | undefined, NullableUncapitalizeDeep<TResult> | undefined>): [readonly unknown[], unknown][];
28
- getQueryData(query: TQuery): NullableUncapitalizeDeep<TResult> | undefined;
29
- getQueriesData(query: Partial<TQuery>): [readonly unknown[], NullableUncapitalizeDeep<TResult> | undefined][];
30
- prefetch(data: TQuery, options?: Omit<FetchQueryOptions<NullableUncapitalizeDeep<TResult>, unknown>, "initialData" | "queryFn" | "queryKey">): Promise<void>;
31
- invalidate(query: Partial<TQuery>): Promise<void>;
32
- cancel(query: Partial<TQuery>): Promise<void>;
33
- optimisticUpdate(updater: Updater<NullableUncapitalizeDeep<TResult> | undefined, NullableUncapitalizeDeep<TResult> | undefined>, query?: Partial<TQuery>): Promise<() => void>;
34
- };
35
- createOperation<TOperation, TResult>(type: string): {
36
- <TContext = unknown>({ onSuccess: onSuccessBase, invalidateQueries, ...options }?: Omit<UseMutationOptions<NullableUncapitalizeDeep<TResult>, unknown, TOperation, TContext>, "mutationFn" | "mutationKey"> & {
37
- invalidateQueries?: QueryKey[];
38
- }): UseMutationResult<NullableUncapitalizeDeep<TResult>, unknown, TOperation, TContext>;
39
- type: string;
40
- key: string[];
41
- fetcher(variables: TOperation): Observable<NullableUncapitalizeDeep<TResult>>;
42
- };
43
- createCommand<TCommand, TErrorCodes extends {
44
- [name: string]: number;
45
- }>(type: string, errorCodes: TErrorCodes): {
46
- <TContext extends Record<string, unknown> = {}>(options?: Omit<UseMutationOptions<ApiSuccess<SuccessfulCommandResult>, ApiResponse<FailedCommandResult<TErrorCodes>>, TCommand, TContext>, "mutationFn" | "mutationKey"> & {
47
- invalidateQueries?: QueryKey[];
48
- handler?: undefined;
49
- optimisticUpdate?: (variables: TCommand) => Promise<() => void>[];
50
- }): UseMutationResult<ApiSuccess<SuccessfulCommandResult>, ApiResponse<FailedCommandResult<TErrorCodes>>, TCommand, TContext>;
51
- <TResult, TContext extends Record<string, unknown> = {}>(options?: Omit<UseMutationOptions<TResult, TResult, TCommand, TContext>, "mutationFn" | "mutationKey"> & {
52
- invalidateQueries?: QueryKey[];
53
- handler: (handler: ValidationErrorsHandler<TErrorCodes & {
54
- success: -1;
55
- failure: -2;
56
- }, never>) => TResult;
57
- optimisticUpdate?: (variables: TCommand) => Promise<() => void>[];
58
- }): UseMutationResult<TResult, TResult, TCommand, TContext>;
59
- type: string;
60
- key: string[];
61
- fetcher(variables: TCommand): Observable<SuccessfulCommandResult>;
62
- call<TResult>(variables: TCommand, handler?: (handler: ValidationErrorsHandler<TErrorCodes & {
63
- success: -1;
64
- failure: -2;
65
- }, never>) => TResult): Observable<ApiSuccess<SuccessfulCommandResult> | TResult>;
66
- mapError(e: unknown): ApiResponse<CommandResult<TErrorCodes>>;
67
- handleResponse<TResult>(handler: (handler: ValidationErrorsHandler<TErrorCodes & {
68
- success: -1;
69
- failure: -2;
70
- }, never>) => TResult): (response: ApiResponse<CommandResult<TErrorCodes>>) => TResult;
71
- };
72
- };
@@ -1,2 +0,0 @@
1
- import { UncapitalizeDeep } from "@leancodepl/utils";
2
- export type NullableUncapitalizeDeep<T> = T extends null ? null : UncapitalizeDeep<T>;
@@ -1 +0,0 @@
1
- export declare function uncapitalizedJSONParse(json: string): any;