@go-avro/avro-js 0.0.2-beta.5 → 0.0.2-beta.50

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.
@@ -0,0 +1,80 @@
1
+ import { AvroQueryClient } from '../../client/QueryClient';
2
+ import { StandardError } from '../../types/error';
3
+ AvroQueryClient.prototype._xhr = function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
4
+ const checkCancelled = () => {
5
+ if (cancelToken?.isCancelled()) {
6
+ return new StandardError(0, 'Request cancelled');
7
+ }
8
+ return null;
9
+ };
10
+ return new Promise((resolve, reject) => {
11
+ this.config.authManager.accessToken().then(token => {
12
+ const cancelErr = checkCancelled();
13
+ if (cancelErr)
14
+ return reject(cancelErr);
15
+ const xhr = new XMLHttpRequest();
16
+ const url = this.config.baseUrl + path;
17
+ xhr.open(method, url, true);
18
+ if (token)
19
+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);
20
+ Object.entries(headers).forEach(([key, value]) => xhr.setRequestHeader(key, value));
21
+ xhr.onload = () => {
22
+ const cancelErr = checkCancelled();
23
+ if (cancelErr)
24
+ return reject(cancelErr);
25
+ if (xhr.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
26
+ this.config.authManager
27
+ .refreshTokens()
28
+ .then(() => {
29
+ this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
30
+ })
31
+ .catch(() => reject(new StandardError(401, 'Unauthorized (refresh failed)')));
32
+ return;
33
+ }
34
+ if (xhr.status >= 200 && xhr.status < 300) {
35
+ try {
36
+ resolve(JSON.parse(xhr.responseText));
37
+ }
38
+ catch {
39
+ resolve(xhr.responseText);
40
+ }
41
+ }
42
+ else {
43
+ if (retryCount < this.config.maxRetries) {
44
+ const delay = this.getDelay(this.config.retryStrategy, retryCount);
45
+ setTimeout(() => {
46
+ this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
47
+ }, delay);
48
+ }
49
+ else {
50
+ let msg = xhr.statusText;
51
+ try {
52
+ const parsed = JSON.parse(xhr.responseText);
53
+ msg = parsed.msg || msg;
54
+ }
55
+ catch {
56
+ console.warn('Failed to parse error response:', xhr.responseText);
57
+ }
58
+ reject(new StandardError(xhr.status, msg));
59
+ }
60
+ }
61
+ };
62
+ xhr.onerror = () => {
63
+ if (retryCount < this.config.maxRetries) {
64
+ const delay = this.getDelay(this.config.retryStrategy, retryCount);
65
+ setTimeout(() => {
66
+ this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
67
+ }, delay);
68
+ }
69
+ else {
70
+ reject(new StandardError(0, 'Network Error'));
71
+ }
72
+ };
73
+ if (this.config.timeout) {
74
+ xhr.timeout = this.config.timeout;
75
+ xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
76
+ }
77
+ xhr.send(body);
78
+ });
79
+ });
80
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,141 @@
1
+ import { useQueryClient, useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../../client/QueryClient';
3
+ AvroQueryClient.prototype.useGetBills = function (companyGuid, body) {
4
+ const queryClient = useQueryClient();
5
+ const result = useInfiniteQuery({
6
+ queryKey: [
7
+ 'bills',
8
+ companyGuid,
9
+ body.query ?? "",
10
+ body.known_ids ?? [],
11
+ body.unknown_ids ?? [],
12
+ body.paid ?? false,
13
+ ],
14
+ initialPageParam: 0,
15
+ getNextPageParam: (lastPage, allPages) => {
16
+ if (lastPage.length < (body.amt ?? 50))
17
+ return undefined;
18
+ return allPages.flat().length; // next offset
19
+ },
20
+ queryFn: ({ pageParam = 0 }) => this.fetchBills(companyGuid, { ...body, offset: pageParam }),
21
+ });
22
+ if (result.data) {
23
+ result.data.pages.forEach((data_page) => {
24
+ data_page.forEach((bill) => {
25
+ queryClient.setQueryData(['bill', bill.id], bill);
26
+ });
27
+ });
28
+ }
29
+ return result;
30
+ };
31
+ AvroQueryClient.prototype.useGetBill = function (billId) {
32
+ return useQuery({
33
+ queryKey: ['bill', billId],
34
+ queryFn: () => this.get(`/bill/${billId}`),
35
+ enabled: Boolean(billId),
36
+ });
37
+ };
38
+ AvroQueryClient.prototype.useCreateBill = function () {
39
+ const queryClient = useQueryClient();
40
+ return useMutation({
41
+ mutationFn: async ({ companyId, data, }) => {
42
+ const body = {
43
+ events: data.line_items.filter(item => item.line_item_type === 'EVENT').map(item => item.id),
44
+ months: data.line_items.filter(item => item.line_item_type === 'SERVICE_MONTH').map(item => item.id),
45
+ line_items: data.line_items.filter(item => item.line_item_type === 'CUSTOM'),
46
+ manual_emails: data.custom_emails,
47
+ users: data.users,
48
+ due_date: data.due_date,
49
+ };
50
+ return this.post(`/company/${companyId}/bill`, JSON.stringify(body), undefined, {
51
+ 'Content-Type': 'application/json',
52
+ });
53
+ },
54
+ onMutate: async ({ companyId }) => {
55
+ await queryClient.cancelQueries({ queryKey: ['bills', companyId] });
56
+ const previousBills = queryClient.getQueryData(['bills', companyId]);
57
+ // TODO: Create a fake bill object for optimistic update and update events and months accordingly
58
+ return { previousBills };
59
+ },
60
+ onError: (_err, _variables, context) => {
61
+ if (context?.previousBills) {
62
+ queryClient.setQueryData(['bills'], context.previousBills);
63
+ }
64
+ },
65
+ onSettled: (_data, _error, variables) => {
66
+ queryClient.invalidateQueries({ queryKey: ['bills', variables.companyId] });
67
+ queryClient.invalidateQueries({ queryKey: ['events', variables.companyId] });
68
+ queryClient.invalidateQueries({ queryKey: ['months', variables.companyId] });
69
+ },
70
+ });
71
+ };
72
+ AvroQueryClient.prototype.useUpdateBill = function () {
73
+ const queryClient = useQueryClient();
74
+ return useMutation({
75
+ mutationFn: ({ billId, updates }) => {
76
+ return this.put(`/bill/${billId}`, JSON.stringify(updates), undefined, {
77
+ "Content-Type": "application/json",
78
+ });
79
+ },
80
+ onMutate: async ({ billId, updates }) => {
81
+ await queryClient.cancelQueries({ queryKey: ['bills'] });
82
+ await queryClient.cancelQueries({ queryKey: ['bill', billId] });
83
+ const previousBills = queryClient.getQueryData(['bills']);
84
+ const previousBill = queryClient.getQueryData(['bill', billId]);
85
+ queryClient.setQueryData(['bill', billId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
86
+ queryClient.setQueriesData({ queryKey: ['bills'] }, (oldData) => {
87
+ if (!oldData)
88
+ return oldData;
89
+ if (oldData.pages) {
90
+ return {
91
+ ...oldData,
92
+ pages: oldData.pages.map((page) => page.map((bill) => bill.id === billId ? { ...bill, ...updates } : bill)),
93
+ };
94
+ }
95
+ if (Array.isArray(oldData)) {
96
+ return oldData.map((bill) => bill.id === billId ? { ...bill, ...updates } : bill);
97
+ }
98
+ return oldData;
99
+ });
100
+ return { previousBills, previousBill };
101
+ },
102
+ onError: (err, variables, context) => {
103
+ const { billId } = variables;
104
+ if (context?.previousBills) {
105
+ queryClient.setQueryData(['bills'], context.previousBills);
106
+ }
107
+ if (context?.previousBill) {
108
+ queryClient.setQueryData(['bill', billId], context.previousBill);
109
+ }
110
+ },
111
+ onSettled: (data, error, variables) => {
112
+ const { billId } = variables;
113
+ queryClient.invalidateQueries({ queryKey: ['bills'] });
114
+ queryClient.invalidateQueries({ queryKey: ['bill', billId] });
115
+ },
116
+ });
117
+ };
118
+ AvroQueryClient.prototype.useDeleteBill = function () {
119
+ const queryClient = useQueryClient();
120
+ return useMutation({
121
+ mutationFn: async ({ billId }) => {
122
+ return this.delete(`/bill/${billId}`);
123
+ },
124
+ onMutate: async ({ billId }) => {
125
+ await queryClient.cancelQueries({ queryKey: ['bills'] });
126
+ const previousBills = queryClient.getQueryData(['bills']);
127
+ // TODO: Create a fake bill object for optimistic update and update events and months accordingly
128
+ return { previousBills };
129
+ },
130
+ onError: (_err, _variables, context) => {
131
+ if (context?.previousBills) {
132
+ queryClient.setQueryData(['bills'], context.previousBills);
133
+ }
134
+ },
135
+ onSettled: (_data, _error) => {
136
+ queryClient.invalidateQueries({ queryKey: ['bills'] });
137
+ queryClient.invalidateQueries({ queryKey: ['events'] });
138
+ queryClient.invalidateQueries({ queryKey: ['months'] });
139
+ },
140
+ });
141
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,51 @@
1
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../../client/QueryClient';
3
+ AvroQueryClient.prototype.useGetCompanies = function (options = {}) {
4
+ return useQuery({
5
+ queryKey: ['/company/list'],
6
+ queryFn: () => this.get('/company/list'),
7
+ ...options,
8
+ });
9
+ };
10
+ AvroQueryClient.prototype.useGetCompany = function (companyId) {
11
+ return useQuery({
12
+ queryKey: ['company', companyId],
13
+ queryFn: () => this.get(`/company/${companyId}`),
14
+ enabled: Boolean(companyId),
15
+ });
16
+ };
17
+ AvroQueryClient.prototype.useUpdateCompany = function () {
18
+ const queryClient = useQueryClient();
19
+ return useMutation({
20
+ mutationFn: async ({ companyId, companyData, }) => {
21
+ return this.put(`/company/${companyId}`, JSON.stringify(companyData), undefined, { "Content-Type": "application/json" });
22
+ },
23
+ onMutate: async ({ companyId, companyData }) => {
24
+ await queryClient.cancelQueries({ queryKey: ['company', companyId] });
25
+ await queryClient.cancelQueries({ queryKey: ['/company/list'] });
26
+ const previousCompany = queryClient.getQueryData(['company', companyId]);
27
+ const previousCompanyList = queryClient.getQueryData(['/company/list']);
28
+ queryClient.setQueryData(['company', companyId], (oldData) => oldData ? { ...oldData, ...companyData } : undefined);
29
+ queryClient.setQueryData(['/company/list'], (oldList) => {
30
+ if (!oldList)
31
+ return oldList;
32
+ return oldList.map((company) => company.id === companyId ? { ...company, ...companyData } : company);
33
+ });
34
+ return { previousCompany, previousCompanyList };
35
+ },
36
+ onError: (_err, variables, context) => {
37
+ const { companyId } = variables;
38
+ if (context?.previousCompany) {
39
+ queryClient.setQueryData(['company', companyId], context.previousCompany);
40
+ }
41
+ if (context?.previousCompanyList) {
42
+ queryClient.setQueryData(['/company/list'], context.previousCompanyList);
43
+ }
44
+ },
45
+ onSettled: (_data, _error, variables) => {
46
+ const { companyId } = variables;
47
+ queryClient.invalidateQueries({ queryKey: ['company', companyId] });
48
+ queryClient.invalidateQueries({ queryKey: ['/company/list'] });
49
+ },
50
+ });
51
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,246 @@
1
+ import { useQueryClient, useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
+ import { AvroQueryClient } from '../../client/QueryClient';
3
+ AvroQueryClient.prototype.useGetEvents = function (companyGuid, body) {
4
+ const queryClient = useQueryClient();
5
+ const result = useInfiniteQuery({
6
+ queryKey: [
7
+ 'events',
8
+ companyGuid,
9
+ body.amt ?? 50,
10
+ body.known_ids ?? [],
11
+ body.unknown_ids ?? [],
12
+ body.query ?? '',
13
+ body.unbilled ?? true,
14
+ body.billed ?? true,
15
+ body.paid ?? true,
16
+ body.jobId ?? '',
17
+ ],
18
+ initialPageParam: 0,
19
+ getNextPageParam: (lastPage, allPages) => {
20
+ if (lastPage.length < (body.amt ?? 50))
21
+ return undefined;
22
+ return allPages.flat().length; // next offset
23
+ },
24
+ queryFn: ({ pageParam = 0 }) => this.fetchEvents(companyGuid, { ...body, offset: pageParam }),
25
+ });
26
+ if (result.data) {
27
+ result.data.pages.forEach((data_page) => {
28
+ data_page.forEach((event) => {
29
+ queryClient.setQueryData(['event', event.id], event);
30
+ });
31
+ });
32
+ }
33
+ return result;
34
+ };
35
+ AvroQueryClient.prototype.useGetEvent = function (eventId) {
36
+ return useQuery({
37
+ queryKey: ['event', eventId],
38
+ queryFn: () => this.get(`/event/${eventId}`),
39
+ enabled: Boolean(eventId),
40
+ });
41
+ };
42
+ AvroQueryClient.prototype.useCreateEvent = function () {
43
+ const queryClient = useQueryClient();
44
+ return useMutation({
45
+ mutationFn: ({ companyId, eventData }) => {
46
+ return this.post(`/company/${companyId}/event`, JSON.stringify(eventData), undefined, {
47
+ "Content-Type": "application/json",
48
+ });
49
+ },
50
+ onMutate: async ({ companyId, eventData }) => {
51
+ await queryClient.cancelQueries({ queryKey: ['events'] });
52
+ const previousEvents = queryClient.getQueryData(['events']);
53
+ queryClient.setQueryData(['events'], (oldData) => {
54
+ if (!oldData)
55
+ return [];
56
+ if (oldData.pages) {
57
+ const firstPage = oldData.pages[0] || [];
58
+ return {
59
+ ...oldData,
60
+ pages: [
61
+ [
62
+ {
63
+ ...eventData,
64
+ id: Math.random().toString(36).substring(2, 11),
65
+ company_id: companyId,
66
+ },
67
+ ...firstPage,
68
+ ],
69
+ ...oldData.pages.slice(1),
70
+ ],
71
+ };
72
+ }
73
+ if (Array.isArray(oldData)) {
74
+ return [
75
+ {
76
+ ...eventData,
77
+ id: Math.random().toString(36).substring(2, 11),
78
+ company_id: companyId,
79
+ },
80
+ ...oldData,
81
+ ];
82
+ }
83
+ return oldData;
84
+ });
85
+ return { previousEvents };
86
+ },
87
+ onError: (err, variables, context) => {
88
+ if (context?.previousEvents) {
89
+ queryClient.setQueryData(['events'], context.previousEvents);
90
+ }
91
+ },
92
+ onSettled: () => {
93
+ queryClient.invalidateQueries({ queryKey: ['events'] });
94
+ },
95
+ });
96
+ };
97
+ AvroQueryClient.prototype.useUpdateEvent = function () {
98
+ const queryClient = useQueryClient();
99
+ return useMutation({
100
+ mutationFn: ({ eventId, updates }) => {
101
+ return this.put(`/event/${eventId}`, JSON.stringify(updates), undefined, {
102
+ "Content-Type": "application/json",
103
+ });
104
+ },
105
+ onMutate: async ({ eventId, updates }) => {
106
+ await queryClient.cancelQueries({ queryKey: ['event', eventId] });
107
+ await queryClient.cancelQueries({ queryKey: ['events'] });
108
+ const previousEvent = queryClient.getQueryData(['event', eventId]);
109
+ const previousEvents = queryClient.getQueryData(['events']);
110
+ queryClient.setQueryData(['event', eventId], (oldData) => oldData ? { ...oldData, ...updates } : undefined);
111
+ queryClient.setQueriesData({ queryKey: ['events'] }, (oldData) => {
112
+ if (!oldData)
113
+ return oldData;
114
+ if (oldData.pages) {
115
+ const updatedPages = oldData.pages.map((page) => page.map((event) => event.id === eventId ? { ...event, ...updates } : event));
116
+ return { ...oldData, pages: updatedPages };
117
+ }
118
+ if (Array.isArray(oldData)) {
119
+ return oldData.map((event) => event.id === eventId ? { ...event, ...updates } : event);
120
+ }
121
+ return oldData;
122
+ });
123
+ return { previousEvent, previousEvents };
124
+ },
125
+ onError: (_err, variables, context) => {
126
+ const { eventId } = variables;
127
+ if (context?.previousEvent) {
128
+ queryClient.setQueryData(['event', eventId], context.previousEvent);
129
+ }
130
+ if (context?.previousEvents) {
131
+ queryClient.setQueryData(['events'], context.previousEvents);
132
+ }
133
+ },
134
+ onSettled: (_data, _error, variables) => {
135
+ const { eventId } = variables;
136
+ queryClient.invalidateQueries({ queryKey: ['event', eventId] });
137
+ queryClient.invalidateQueries({ queryKey: ['events'] });
138
+ },
139
+ });
140
+ };
141
+ AvroQueryClient.prototype.useUpdateEvents = function () {
142
+ const queryClient = useQueryClient();
143
+ return useMutation({
144
+ mutationFn: async ({ companyId, events, action, }) => {
145
+ const eventIds = events.map(event => event.id);
146
+ return this.put(`/company/${companyId}/events`, JSON.stringify({
147
+ events: eventIds,
148
+ billed: true,
149
+ paid: action === "paid",
150
+ }), undefined, {
151
+ "Content-Type": "application/json",
152
+ });
153
+ },
154
+ onMutate: async ({ events, action }) => {
155
+ await queryClient.cancelQueries({ queryKey: ['events'] });
156
+ await queryClient.cancelQueries({ queryKey: ['event'] });
157
+ const previousEvents = queryClient.getQueryData(['events']);
158
+ const previousEventObjs = events.map(event => queryClient.getQueryData(['event', event.id]));
159
+ const eventIds = events.map(event => event.id);
160
+ // Optimistically update individual event cache
161
+ eventIds.forEach((eventId, idx) => {
162
+ queryClient.setQueryData(['event', eventId], (oldData) => {
163
+ return oldData
164
+ ? { ...oldData, billed: true, paid: action === "paid" }
165
+ : oldData;
166
+ });
167
+ });
168
+ // Optimistically update events list cache
169
+ queryClient.setQueriesData({ queryKey: ['events'] }, (oldData) => {
170
+ if (!oldData)
171
+ return oldData;
172
+ if (oldData.pages) {
173
+ const updatedPages = oldData.pages.map((page) => page.map((event) => eventIds.includes(event.id)
174
+ ? { ...event, billed: true, paid: action === "paid" }
175
+ : event));
176
+ return { ...oldData, pages: updatedPages };
177
+ }
178
+ if (Array.isArray(oldData)) {
179
+ return oldData.map((event) => eventIds.includes(event.id)
180
+ ? { ...event, billed: true, paid: action === "paid" }
181
+ : event);
182
+ }
183
+ return oldData;
184
+ });
185
+ return { previousEvents, previousEventObjs };
186
+ },
187
+ onError: (err, variables, context) => {
188
+ if (context?.previousEvents) {
189
+ queryClient.setQueryData(['events'], context.previousEvents);
190
+ }
191
+ if (context?.previousEventObjs) {
192
+ context.previousEventObjs.forEach((eventObj) => {
193
+ queryClient.setQueryData(['event', eventObj.id], eventObj);
194
+ });
195
+ }
196
+ },
197
+ onSettled: () => {
198
+ queryClient.invalidateQueries({ queryKey: ['events'] });
199
+ queryClient.invalidateQueries({ queryKey: ['event'] });
200
+ },
201
+ });
202
+ };
203
+ AvroQueryClient.prototype.useDeleteEvent = function () {
204
+ const queryClient = useQueryClient();
205
+ return useMutation({
206
+ mutationFn: async ({ eventId, }) => {
207
+ return this.delete(`/event/${eventId}`, undefined, {
208
+ "Content-Type": "application/json",
209
+ });
210
+ },
211
+ onMutate: async ({ eventId }) => {
212
+ await queryClient.cancelQueries({ queryKey: ['events'] });
213
+ await queryClient.cancelQueries({ queryKey: ['event', eventId] });
214
+ const previousEvents = queryClient.getQueryData(['events']);
215
+ const previousEvent = queryClient.getQueryData(['event', eventId]);
216
+ queryClient.setQueryData(['event', eventId], undefined);
217
+ queryClient.setQueriesData({ queryKey: ['events'] }, (oldData) => {
218
+ if (!oldData)
219
+ return oldData;
220
+ if (oldData.pages) {
221
+ const updatedPages = oldData.pages.map((page) => page.filter((event) => event.id !== eventId));
222
+ return { ...oldData, pages: updatedPages };
223
+ }
224
+ if (Array.isArray(oldData)) {
225
+ return oldData.filter((event) => event.id !== eventId);
226
+ }
227
+ return oldData;
228
+ });
229
+ return { previousEvents, previousEvent };
230
+ },
231
+ onError: (_err, variables, context) => {
232
+ const { eventId } = variables;
233
+ if (context?.previousEvents) {
234
+ queryClient.setQueryData(['events'], context.previousEvents);
235
+ }
236
+ if (context?.previousEvent) {
237
+ queryClient.setQueryData(['event', eventId], context.previousEvent);
238
+ }
239
+ },
240
+ onSettled: (_data, _error, variables) => {
241
+ const { eventId } = variables;
242
+ queryClient.invalidateQueries({ queryKey: ['events'] });
243
+ queryClient.invalidateQueries({ queryKey: ['event', eventId] });
244
+ },
245
+ });
246
+ };
@@ -0,0 +1 @@
1
+ export {};