@go-avro/avro-js 0.1.15 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/AuthManager.d.ts +28 -0
- package/dist/auth/AuthManager.js +119 -43
- package/dist/client/QueryClient.d.ts +56 -1
- package/dist/client/QueryClient.js +260 -79
- package/dist/client/cache.d.ts +24 -0
- package/dist/client/cache.js +51 -0
- package/dist/client/core/fetch.js +58 -49
- package/dist/client/core/policy.d.ts +17 -0
- package/dist/client/core/policy.js +35 -0
- package/dist/client/core/xhr.js +16 -14
- package/dist/client/hooks/bills.js +10 -14
- package/dist/client/hooks/catalog_items.js +18 -8
- package/dist/client/hooks/chats.js +2 -8
- package/dist/client/hooks/companies.js +11 -5
- package/dist/client/hooks/events.js +36 -30
- package/dist/client/hooks/groups.js +11 -26
- package/dist/client/hooks/jobs.js +3 -8
- package/dist/client/hooks/labels.js +11 -26
- package/dist/client/hooks/messages.js +3 -8
- package/dist/client/hooks/months.js +28 -22
- package/dist/client/hooks/payouts.js +3 -8
- package/dist/client/hooks/prepayments.js +28 -22
- package/dist/client/hooks/proposal.js +1 -0
- package/dist/client/hooks/routes.js +8 -6
- package/dist/client/hooks/sessions.js +11 -27
- package/dist/client/hooks/skills.js +6 -4
- package/dist/client/hooks/teams.js +6 -4
- package/dist/client/hooks/timecards.js +7 -7
- package/dist/client/hooks/waivers.js +6 -4
- package/dist/client/persist.js +21 -2
- package/dist/client/realtime.d.ts +12 -0
- package/dist/client/realtime.js +160 -46
- package/dist/types/api/Company.d.ts +2 -0
- package/dist/types/api/LineItem.d.ts +4 -0
- package/dist/types/api/LineItem.js +8 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +7 -2
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small cache helpers shared by the hooks: namespace snapshots for
|
|
3
|
+
* optimistic-update rollback, detail seeding from list fetches, and
|
|
4
|
+
* optimistic-row cleanup.
|
|
5
|
+
*/
|
|
6
|
+
import { isListKey } from './realtime.js';
|
|
7
|
+
/**
|
|
8
|
+
* Snapshot every cached query under `ns` (lists and details). A plain
|
|
9
|
+
* `getQueryData([ns])` only reads the exact key `[ns]`, which no hook
|
|
10
|
+
* uses, so rollbacks built on it were no-ops.
|
|
11
|
+
*/
|
|
12
|
+
export function snapshotNs(qc, ns) {
|
|
13
|
+
return qc.getQueriesData({ queryKey: [ns] });
|
|
14
|
+
}
|
|
15
|
+
/** Restore a snapshot taken with `snapshotNs`. */
|
|
16
|
+
export function restoreNs(qc, snapshot) {
|
|
17
|
+
snapshot?.forEach(([key, data]) => qc.setQueryData(key, data));
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Seed `[ns, id]` detail entries from a fetched list. Call from inside a
|
|
21
|
+
* `queryFn` (never during render).
|
|
22
|
+
*/
|
|
23
|
+
export function seedDetails(qc, ns, items) {
|
|
24
|
+
if (qc && Array.isArray(items)) {
|
|
25
|
+
for (const item of items) {
|
|
26
|
+
if (item?.id)
|
|
27
|
+
qc.setQueryData([ns, item.id], item);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return items;
|
|
31
|
+
}
|
|
32
|
+
/** Remove an optimistic row (by its temporary id) from every list in `ns`. */
|
|
33
|
+
export function removeOptimisticRow(qc, ns, tempId) {
|
|
34
|
+
qc.removeQueries({ queryKey: [ns, tempId], exact: true });
|
|
35
|
+
qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => {
|
|
36
|
+
if (!old)
|
|
37
|
+
return old;
|
|
38
|
+
if (Array.isArray(old)) {
|
|
39
|
+
return old.some((x) => x?.id === tempId)
|
|
40
|
+
? old.filter((x) => x?.id !== tempId)
|
|
41
|
+
: old;
|
|
42
|
+
}
|
|
43
|
+
if (Array.isArray(old.pages)) {
|
|
44
|
+
return {
|
|
45
|
+
...old,
|
|
46
|
+
pages: old.pages.map((p) => Array.isArray(p) ? p.filter((x) => x?.id !== tempId) : p),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
return old;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
@@ -2,66 +2,83 @@ import { AvroQueryClient } from '../QueryClient.js';
|
|
|
2
2
|
import { StandardError } from '../../types/error.js';
|
|
3
3
|
import { AuthState } from '../../types/auth.js';
|
|
4
4
|
import { AVRO_JS_VERSION } from '../../version.js';
|
|
5
|
+
import { cancelledError, isCancelledError, refreshFailureError, shouldRetry, } from './policy.js';
|
|
5
6
|
AvroQueryClient.prototype._fetch = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
|
|
6
7
|
const checkCancelled = () => {
|
|
8
|
+
if (cancelToken?.isCancelled()) {
|
|
9
|
+
throw cancelledError();
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
let attempt = retryCount;
|
|
13
|
+
// A post-401 token refresh gets one replay outside the retry budget.
|
|
14
|
+
let refreshed = false;
|
|
15
|
+
for (;;) {
|
|
16
|
+
let response;
|
|
7
17
|
try {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
18
|
+
checkCancelled();
|
|
19
|
+
const token = this.getAuthState() === AuthState.AUTHENTICATED
|
|
20
|
+
? await this.config.authManager.accessToken()
|
|
21
|
+
: undefined;
|
|
22
|
+
checkCancelled();
|
|
23
|
+
const url = this.config.baseUrl + path;
|
|
24
|
+
const requestHeaders = {
|
|
25
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
26
|
+
'X-Avro-Js-Version': AVRO_JS_VERSION,
|
|
27
|
+
...(this.config.clientId ? { 'X-Avro-Client-Id': this.config.clientId } : {}),
|
|
28
|
+
...(this.config.clientVersion
|
|
29
|
+
? { 'X-Avro-Client-Version': this.config.clientVersion }
|
|
30
|
+
: {}),
|
|
31
|
+
...headers,
|
|
32
|
+
};
|
|
33
|
+
response = await fetch(url, { method, headers: requestHeaders, body });
|
|
11
34
|
}
|
|
12
35
|
catch (error) {
|
|
13
|
-
|
|
36
|
+
if (isCancelledError(error) || error instanceof StandardError)
|
|
37
|
+
throw error;
|
|
38
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
39
|
+
console.error('Fetch error:', message);
|
|
40
|
+
// Network failure: the request may or may not have reached the server.
|
|
41
|
+
if (shouldRetry(0, isIdempotent) && attempt < this.config.maxRetries) {
|
|
42
|
+
await this.sleep(this.getDelay(this.config.retryStrategy, attempt));
|
|
43
|
+
attempt++;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
throw new StandardError(0, `Request failed: ${message}`);
|
|
14
47
|
}
|
|
15
|
-
};
|
|
16
|
-
try {
|
|
17
|
-
checkCancelled();
|
|
18
|
-
const token = this.getAuthState() === AuthState.AUTHENTICATED
|
|
19
|
-
? await this.config.authManager.accessToken()
|
|
20
|
-
: undefined;
|
|
21
|
-
checkCancelled();
|
|
22
|
-
const url = this.config.baseUrl + path;
|
|
23
|
-
const requestHeaders = {
|
|
24
|
-
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
25
|
-
'X-Avro-Js-Version': AVRO_JS_VERSION,
|
|
26
|
-
...(this.config.clientId ? { 'X-Avro-Client-Id': this.config.clientId } : {}),
|
|
27
|
-
...(this.config.clientVersion
|
|
28
|
-
? { 'X-Avro-Client-Version': this.config.clientVersion }
|
|
29
|
-
: {}),
|
|
30
|
-
...headers,
|
|
31
|
-
};
|
|
32
|
-
const options = {
|
|
33
|
-
method,
|
|
34
|
-
headers: requestHeaders,
|
|
35
|
-
body,
|
|
36
|
-
};
|
|
37
|
-
const response = await fetch(url, options);
|
|
38
48
|
if (response.ok) {
|
|
49
|
+
this._noteRequestSucceeded();
|
|
39
50
|
const contentType = response.headers.get('content-type') ?? '';
|
|
40
51
|
if (contentType.includes('application/pdf') ||
|
|
41
52
|
contentType.includes('application/octet-stream')) {
|
|
42
|
-
return response.blob();
|
|
53
|
+
return (await response.blob());
|
|
43
54
|
}
|
|
44
55
|
const text = await response.text();
|
|
45
56
|
if (!text) {
|
|
46
57
|
return undefined;
|
|
47
58
|
}
|
|
48
|
-
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(text);
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
throw new StandardError(0, `Failed to parse successful response: ${e?.message}`);
|
|
64
|
+
}
|
|
49
65
|
}
|
|
50
66
|
if (response.status === 401 &&
|
|
51
|
-
|
|
52
|
-
retryCount === 0 &&
|
|
67
|
+
!refreshed &&
|
|
53
68
|
this.getAuthState() === AuthState.AUTHENTICATED) {
|
|
54
|
-
|
|
55
|
-
|
|
69
|
+
refreshed = true;
|
|
70
|
+
try {
|
|
71
|
+
await this.config.authManager.refreshTokens();
|
|
72
|
+
}
|
|
73
|
+
catch (refreshError) {
|
|
74
|
+
throw refreshFailureError(refreshError);
|
|
75
|
+
}
|
|
76
|
+
continue;
|
|
56
77
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (!isClientError && retryCount < this.config.maxRetries) {
|
|
62
|
-
const delay = this.getDelay(this.config.retryStrategy, retryCount);
|
|
63
|
-
await this.sleep(delay);
|
|
64
|
-
return this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1);
|
|
78
|
+
if (shouldRetry(response.status, isIdempotent) && attempt < this.config.maxRetries) {
|
|
79
|
+
await this.sleep(this.getDelay(this.config.retryStrategy, attempt));
|
|
80
|
+
attempt++;
|
|
81
|
+
continue;
|
|
65
82
|
}
|
|
66
83
|
let errorMessage = response.statusText;
|
|
67
84
|
let errorBody;
|
|
@@ -75,12 +92,4 @@ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelTok
|
|
|
75
92
|
}
|
|
76
93
|
throw new StandardError(response.status, errorMessage, errorBody);
|
|
77
94
|
}
|
|
78
|
-
catch (error) {
|
|
79
|
-
if (error instanceof StandardError) {
|
|
80
|
-
throw error;
|
|
81
|
-
}
|
|
82
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
83
|
-
console.error('Fetch error:', message);
|
|
84
|
-
throw new StandardError(0, `Request failed: ${message}`);
|
|
85
|
-
}
|
|
86
95
|
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { StandardError } from '../../types/error.js';
|
|
2
|
+
/** A cancelled request: never retried, never rewrapped. */
|
|
3
|
+
export declare function cancelledError(): StandardError;
|
|
4
|
+
export declare function isCancelledError(err: unknown): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Whether a failed attempt may be retried. 429 means the server refused
|
|
7
|
+
* the request without processing it, so it's safe for any method.
|
|
8
|
+
* Everything else that's retryable (network error / timeout / 408 / 5xx)
|
|
9
|
+
* may have reached the server, so only idempotent requests retry.
|
|
10
|
+
*/
|
|
11
|
+
export declare function shouldRetry(status: number, isIdempotent: boolean): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The error to surface when refreshing tokens after a 401 failed: a
|
|
14
|
+
* definitive failure stays a 401 (the session is over); a transient one
|
|
15
|
+
* (offline / 5xx) surfaces as-is so callers don't treat it as a logout.
|
|
16
|
+
*/
|
|
17
|
+
export declare function refreshFailureError(refreshError: unknown): StandardError;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { isDefinitiveAuthFailure } from '../../auth/AuthManager.js';
|
|
2
|
+
import { StandardError } from '../../types/error.js';
|
|
3
|
+
/** A cancelled request: never retried, never rewrapped. */
|
|
4
|
+
export function cancelledError() {
|
|
5
|
+
const err = new StandardError(0, 'Request cancelled');
|
|
6
|
+
err.cancelled = true;
|
|
7
|
+
return err;
|
|
8
|
+
}
|
|
9
|
+
export function isCancelledError(err) {
|
|
10
|
+
return Boolean(err?.cancelled);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Whether a failed attempt may be retried. 429 means the server refused
|
|
14
|
+
* the request without processing it, so it's safe for any method.
|
|
15
|
+
* Everything else that's retryable (network error / timeout / 408 / 5xx)
|
|
16
|
+
* may have reached the server, so only idempotent requests retry.
|
|
17
|
+
*/
|
|
18
|
+
export function shouldRetry(status, isIdempotent) {
|
|
19
|
+
if (status === 429)
|
|
20
|
+
return true;
|
|
21
|
+
if (!isIdempotent)
|
|
22
|
+
return false;
|
|
23
|
+
return status === 0 || status === 408 || status >= 500;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The error to surface when refreshing tokens after a 401 failed: a
|
|
27
|
+
* definitive failure stays a 401 (the session is over); a transient one
|
|
28
|
+
* (offline / 5xx) surfaces as-is so callers don't treat it as a logout.
|
|
29
|
+
*/
|
|
30
|
+
export function refreshFailureError(refreshError) {
|
|
31
|
+
if (isDefinitiveAuthFailure(refreshError) || !(refreshError instanceof StandardError)) {
|
|
32
|
+
return new StandardError(401, 'Unauthorized (refresh failed)');
|
|
33
|
+
}
|
|
34
|
+
return refreshError;
|
|
35
|
+
}
|
package/dist/client/core/xhr.js
CHANGED
|
@@ -2,14 +2,19 @@ import { AvroQueryClient } from '../QueryClient.js';
|
|
|
2
2
|
import { StandardError } from '../../types/error.js';
|
|
3
3
|
import { AuthState } from '../../types/auth.js';
|
|
4
4
|
import { AVRO_JS_VERSION } from '../../version.js';
|
|
5
|
+
import { cancelledError, isCancelledError, refreshFailureError, shouldRetry, } from './policy.js';
|
|
5
6
|
AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount, progressUpdateCallback) {
|
|
6
7
|
const maxRetries = retryCount ?? this.config.maxRetries;
|
|
7
8
|
const checkCancelled = () => {
|
|
8
9
|
if (cancelToken?.isCancelled()) {
|
|
9
|
-
throw
|
|
10
|
+
throw cancelledError();
|
|
10
11
|
}
|
|
11
12
|
};
|
|
12
|
-
|
|
13
|
+
let attempt = 0;
|
|
14
|
+
// A post-401 token refresh gets one replay that doesn't count against
|
|
15
|
+
// maxRetries (so it works with maxRetries: 0).
|
|
16
|
+
let refreshed = false;
|
|
17
|
+
for (;;) {
|
|
13
18
|
try {
|
|
14
19
|
checkCancelled();
|
|
15
20
|
const token = this.getAuthState() === AuthState.AUTHENTICATED
|
|
@@ -83,9 +88,12 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
|
|
|
83
88
|
}
|
|
84
89
|
xhr.send(body);
|
|
85
90
|
});
|
|
91
|
+
this._noteRequestSucceeded();
|
|
86
92
|
return result;
|
|
87
93
|
}
|
|
88
94
|
catch (error) {
|
|
95
|
+
if (isCancelledError(error))
|
|
96
|
+
throw error;
|
|
89
97
|
console.error('xhr error:', error);
|
|
90
98
|
if (!(error instanceof StandardError)) {
|
|
91
99
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -93,30 +101,24 @@ AvroQueryClient.prototype._xhr = async function (method, path, body, cancelToken
|
|
|
93
101
|
throw new StandardError(0, `An unexpected error occurred: ${message}`);
|
|
94
102
|
}
|
|
95
103
|
if (error.status === 401 &&
|
|
96
|
-
|
|
97
|
-
attempt === 0 &&
|
|
104
|
+
!refreshed &&
|
|
98
105
|
this.getAuthState() === AuthState.AUTHENTICATED) {
|
|
99
|
-
|
|
106
|
+
refreshed = true;
|
|
100
107
|
try {
|
|
101
108
|
await this.config.authManager.refreshTokens();
|
|
102
|
-
continue;
|
|
103
109
|
}
|
|
104
110
|
catch (refreshError) {
|
|
105
|
-
throw
|
|
111
|
+
throw refreshFailureError(refreshError);
|
|
106
112
|
}
|
|
113
|
+
continue;
|
|
107
114
|
}
|
|
108
|
-
|
|
109
|
-
error.status < 500 &&
|
|
110
|
-
error.status !== 408 &&
|
|
111
|
-
error.status !== 429;
|
|
112
|
-
if (error.status === 401 || isClientError || attempt >= maxRetries) {
|
|
113
|
-
console.error('Not retrying request, throwing error.');
|
|
115
|
+
if (!shouldRetry(error.status, isIdempotent) || attempt >= maxRetries) {
|
|
114
116
|
throw error;
|
|
115
117
|
}
|
|
116
118
|
const delay = this.getDelay(this.config.retryStrategy, attempt);
|
|
117
119
|
console.error(`Retrying request in ${delay} ms...`);
|
|
120
|
+
attempt++;
|
|
118
121
|
await this.sleep(delay);
|
|
119
122
|
}
|
|
120
123
|
}
|
|
121
|
-
throw new StandardError(0, 'Request failed after maximum retries.');
|
|
122
124
|
};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
|
|
2
2
|
import { AvroQueryClient } from '../QueryClient.js';
|
|
3
|
+
import { seedDetails } from '../cache.js';
|
|
4
|
+
import { restoreNs, snapshotNs } from '../cache.js';
|
|
3
5
|
import { keys } from '../realtime.js';
|
|
4
6
|
import { Bill } from '../../types/api.js';
|
|
5
7
|
AvroQueryClient.prototype.useGetBills = function (body) {
|
|
@@ -26,15 +28,9 @@ AvroQueryClient.prototype.useGetBills = function (body) {
|
|
|
26
28
|
return undefined;
|
|
27
29
|
return allPages.flat().length; // next offset
|
|
28
30
|
},
|
|
29
|
-
queryFn: ({ pageParam = 0 }) => this.fetchBills({ ...body, offset: pageParam }).then((bills) => bills.map((bill) => new Bill(bill))),
|
|
31
|
+
queryFn: ({ pageParam = 0 }) => this.fetchBills({ ...body, offset: pageParam }).then((bills) => seedDetails(queryClient, 'bills', bills.map((bill) => new Bill(bill)))),
|
|
32
|
+
enabled: Boolean(this.companyId),
|
|
30
33
|
});
|
|
31
|
-
if (result.data) {
|
|
32
|
-
result.data.pages.forEach((data_page) => {
|
|
33
|
-
data_page.forEach((bill) => {
|
|
34
|
-
queryClient.setQueryData(['bills', bill.id], bill);
|
|
35
|
-
});
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
34
|
return result;
|
|
39
35
|
};
|
|
40
36
|
AvroQueryClient.prototype.useGetBill = function (billId) {
|
|
@@ -71,7 +67,7 @@ AvroQueryClient.prototype.useCreateBill = function () {
|
|
|
71
67
|
await queryClient.cancelQueries({
|
|
72
68
|
queryKey: ['bills', this.companyId],
|
|
73
69
|
});
|
|
74
|
-
const previousBills = queryClient
|
|
70
|
+
const previousBills = snapshotNs(queryClient, 'bills');
|
|
75
71
|
// TODO: Create a fake bill object for optimistic update and update events and months accordingly
|
|
76
72
|
return { previousBills };
|
|
77
73
|
},
|
|
@@ -80,7 +76,7 @@ AvroQueryClient.prototype.useCreateBill = function () {
|
|
|
80
76
|
},
|
|
81
77
|
onError: (_err, _variables, context) => {
|
|
82
78
|
if (context?.previousBills) {
|
|
83
|
-
queryClient
|
|
79
|
+
restoreNs(queryClient, context.previousBills);
|
|
84
80
|
}
|
|
85
81
|
},
|
|
86
82
|
});
|
|
@@ -100,7 +96,7 @@ AvroQueryClient.prototype.useUpdateBill = function () {
|
|
|
100
96
|
onMutate: async ({ billId, updates }) => {
|
|
101
97
|
await queryClient.cancelQueries({ queryKey: ['bills'] });
|
|
102
98
|
await queryClient.cancelQueries({ queryKey: ['bills', billId] });
|
|
103
|
-
const previousBills = queryClient
|
|
99
|
+
const previousBills = snapshotNs(queryClient, 'bills');
|
|
104
100
|
const previousBill = queryClient.getQueryData(['bills', billId]);
|
|
105
101
|
queryClient.setQueryData(['bills', billId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
|
|
106
102
|
queryClient.setQueriesData({ queryKey: ['bills'] }, (oldData) => {
|
|
@@ -125,7 +121,7 @@ AvroQueryClient.prototype.useUpdateBill = function () {
|
|
|
125
121
|
onError: (err, variables, context) => {
|
|
126
122
|
const { billId } = variables;
|
|
127
123
|
if (context?.previousBills) {
|
|
128
|
-
queryClient
|
|
124
|
+
restoreNs(queryClient, context.previousBills);
|
|
129
125
|
}
|
|
130
126
|
if (context?.previousBill) {
|
|
131
127
|
queryClient.setQueryData(['bills', billId], context.previousBill);
|
|
@@ -158,7 +154,7 @@ AvroQueryClient.prototype.useDeleteBill = function () {
|
|
|
158
154
|
},
|
|
159
155
|
onMutate: async ({ billId }) => {
|
|
160
156
|
await queryClient.cancelQueries({ queryKey: ['bills'] });
|
|
161
|
-
const previousBills = queryClient
|
|
157
|
+
const previousBills = snapshotNs(queryClient, 'bills');
|
|
162
158
|
// TODO: Create a fake bill object for optimistic update and update events and months accordingly
|
|
163
159
|
return { previousBills };
|
|
164
160
|
},
|
|
@@ -167,7 +163,7 @@ AvroQueryClient.prototype.useDeleteBill = function () {
|
|
|
167
163
|
},
|
|
168
164
|
onError: (_err, _variables, context) => {
|
|
169
165
|
if (context?.previousBills) {
|
|
170
|
-
queryClient
|
|
166
|
+
restoreNs(queryClient, context.previousBills);
|
|
171
167
|
}
|
|
172
168
|
},
|
|
173
169
|
});
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { useQuery, useMutation } from '@tanstack/react-query';
|
|
2
2
|
import { AvroQueryClient } from '../QueryClient.js';
|
|
3
|
+
import { restoreNs, snapshotNs } from '../cache.js';
|
|
4
|
+
import { StandardError } from '../../types/error.js';
|
|
3
5
|
AvroQueryClient.prototype.useCreateCatalogItem = function () {
|
|
4
6
|
const queryClient = this.getQueryClient();
|
|
5
7
|
return useMutation({
|
|
@@ -16,7 +18,7 @@ AvroQueryClient.prototype.useCreateCatalogItem = function () {
|
|
|
16
18
|
await queryClient.cancelQueries({
|
|
17
19
|
queryKey: ['catalog_items', this.companyId],
|
|
18
20
|
});
|
|
19
|
-
const previousItems = queryClient
|
|
21
|
+
const previousItems = snapshotNs(queryClient, 'catalog_items');
|
|
20
22
|
return { previousItems };
|
|
21
23
|
},
|
|
22
24
|
onSuccess: () => {
|
|
@@ -24,7 +26,7 @@ AvroQueryClient.prototype.useCreateCatalogItem = function () {
|
|
|
24
26
|
},
|
|
25
27
|
onError: (_err, _variables, context) => {
|
|
26
28
|
if (context?.previousItems) {
|
|
27
|
-
queryClient
|
|
29
|
+
restoreNs(queryClient, context.previousItems);
|
|
28
30
|
}
|
|
29
31
|
},
|
|
30
32
|
});
|
|
@@ -46,7 +48,7 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
|
|
|
46
48
|
await queryClient.cancelQueries({
|
|
47
49
|
queryKey: ['catalog_items', catalogItemId],
|
|
48
50
|
});
|
|
49
|
-
const previousItems = queryClient
|
|
51
|
+
const previousItems = snapshotNs(queryClient, 'catalog_items');
|
|
50
52
|
const previousItem = queryClient.getQueryData(['catalog_items', catalogItemId]);
|
|
51
53
|
queryClient.setQueryData(['catalog_items', catalogItemId], (oldData) => oldData ? { ...oldData, ...data } : undefined);
|
|
52
54
|
queryClient.setQueriesData({ queryKey: ['catalog_items'] }, (oldData) => {
|
|
@@ -71,7 +73,7 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
|
|
|
71
73
|
onError: (err, variables, context) => {
|
|
72
74
|
const { catalogItemId } = variables;
|
|
73
75
|
if (context?.previousItems) {
|
|
74
|
-
queryClient
|
|
76
|
+
restoreNs(queryClient, context.previousItems);
|
|
75
77
|
}
|
|
76
78
|
if (context?.previousItem) {
|
|
77
79
|
queryClient.setQueryData(['catalog_items', catalogItemId], context.previousItem);
|
|
@@ -82,8 +84,16 @@ AvroQueryClient.prototype.useUpdateCatalogItem = function () {
|
|
|
82
84
|
AvroQueryClient.prototype.useGetCatalogItem = function (catalogItemId) {
|
|
83
85
|
return useQuery({
|
|
84
86
|
queryKey: ['catalog_items', catalogItemId],
|
|
85
|
-
|
|
86
|
-
|
|
87
|
+
// There is no `GET /catalog_item/<id>`: catalog items are embedded
|
|
88
|
+
// in the company payload.
|
|
89
|
+
queryFn: async () => {
|
|
90
|
+
const company = await this.get({ path: `/company/${this.companyId}` });
|
|
91
|
+
const item = company?.catalog_items?.find((ci) => ci.id === catalogItemId);
|
|
92
|
+
if (!item)
|
|
93
|
+
throw new StandardError(404, 'Catalog item not found');
|
|
94
|
+
return item;
|
|
95
|
+
},
|
|
96
|
+
enabled: Boolean(catalogItemId) && Boolean(this.companyId),
|
|
87
97
|
});
|
|
88
98
|
};
|
|
89
99
|
AvroQueryClient.prototype.useDeleteCatalogItem = function () {
|
|
@@ -96,7 +106,7 @@ AvroQueryClient.prototype.useDeleteCatalogItem = function () {
|
|
|
96
106
|
},
|
|
97
107
|
onMutate: async ({ catalogItemId }) => {
|
|
98
108
|
await queryClient.cancelQueries({ queryKey: ['catalog_items'] });
|
|
99
|
-
const previousItems = queryClient
|
|
109
|
+
const previousItems = snapshotNs(queryClient, 'catalog_items');
|
|
100
110
|
return { previousItems };
|
|
101
111
|
},
|
|
102
112
|
onSuccess: () => {
|
|
@@ -104,7 +114,7 @@ AvroQueryClient.prototype.useDeleteCatalogItem = function () {
|
|
|
104
114
|
},
|
|
105
115
|
onError: (_err, _variables, context) => {
|
|
106
116
|
if (context?.previousItems) {
|
|
107
|
-
queryClient
|
|
117
|
+
restoreNs(queryClient, context.previousItems);
|
|
108
118
|
}
|
|
109
119
|
},
|
|
110
120
|
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
|
2
2
|
import { AvroQueryClient } from '../QueryClient.js';
|
|
3
|
+
import { seedDetails } from '../cache.js';
|
|
3
4
|
import { keys } from '../realtime.js';
|
|
4
5
|
AvroQueryClient.prototype.useGetChats = function (body) {
|
|
5
6
|
const queryClient = this.getQueryClient();
|
|
@@ -16,15 +17,8 @@ AvroQueryClient.prototype.useGetChats = function (body) {
|
|
|
16
17
|
return undefined;
|
|
17
18
|
return allPages.flat().length; // next offset
|
|
18
19
|
},
|
|
19
|
-
queryFn: ({ pageParam = 0 }) => this.fetchChats({ ...body, offset: pageParam }),
|
|
20
|
+
queryFn: ({ pageParam = 0 }) => this.fetchChats({ ...body, offset: pageParam }).then((chats) => seedDetails(queryClient, 'chats', chats)),
|
|
20
21
|
});
|
|
21
|
-
if (result.data) {
|
|
22
|
-
result.data.pages.forEach((data_page) => {
|
|
23
|
-
data_page.forEach((chat) => {
|
|
24
|
-
queryClient.setQueryData(['chats', chat.id], chat);
|
|
25
|
-
});
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
22
|
return result;
|
|
29
23
|
};
|
|
30
24
|
AvroQueryClient.prototype.useGetChat = function (chatId) {
|
|
@@ -9,12 +9,13 @@ AvroQueryClient.prototype.useGetCompanies = function (options = {}) {
|
|
|
9
9
|
const companiesPromise = this.get({
|
|
10
10
|
path: `/company/list`,
|
|
11
11
|
});
|
|
12
|
-
companiesPromise.then((companies) => {
|
|
12
|
+
return companiesPromise.then(async (companies) => {
|
|
13
13
|
if (!companies.find((c) => c.id === this.companyId) && companies.length > 0) {
|
|
14
|
-
|
|
14
|
+
// setCompanyId persists the choice and joins its socket room.
|
|
15
|
+
await this.setCompanyId(companies[0].id);
|
|
15
16
|
}
|
|
17
|
+
return companies;
|
|
16
18
|
});
|
|
17
|
-
return companiesPromise;
|
|
18
19
|
},
|
|
19
20
|
enabled: this.getAuthState() === AuthState.AUTHENTICATED,
|
|
20
21
|
...options,
|
|
@@ -162,9 +163,13 @@ AvroQueryClient.prototype.useRemoveUserCompany = function () {
|
|
|
162
163
|
await queryClient.cancelQueries({
|
|
163
164
|
queryKey: ['companies', this.companyId],
|
|
164
165
|
});
|
|
166
|
+
await queryClient.cancelQueries({ queryKey: ['users', 'company'] });
|
|
165
167
|
const previousCompany = queryClient.getQueryData(['companies', this.companyId]);
|
|
166
|
-
queryClient.
|
|
167
|
-
|
|
168
|
+
const previousMembers = queryClient.getQueriesData({ queryKey: ['users', 'company'] });
|
|
169
|
+
// Members are memberships; `userId` is the user's id, not the
|
|
170
|
+
// membership's.
|
|
171
|
+
queryClient.setQueriesData({ queryKey: ['users', 'company'] }, (old) => Array.isArray(old) ? old.filter((member) => member.user?.id !== userId) : old);
|
|
172
|
+
return { previousCompany, previousMembers };
|
|
168
173
|
},
|
|
169
174
|
onSuccess: () => {
|
|
170
175
|
this.syncAfterMutation('member', 'company');
|
|
@@ -173,6 +178,7 @@ AvroQueryClient.prototype.useRemoveUserCompany = function () {
|
|
|
173
178
|
if (context?.previousCompany) {
|
|
174
179
|
queryClient.setQueryData(['companies', this.companyId], context.previousCompany);
|
|
175
180
|
}
|
|
181
|
+
context?.previousMembers?.forEach(([key, data]) => queryClient.setQueryData(key, data));
|
|
176
182
|
},
|
|
177
183
|
});
|
|
178
184
|
};
|