@go-avro/avro-js 0.1.0 → 0.1.1

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.
@@ -77,6 +77,10 @@ declare module '../client/QueryClient' {
77
77
  useGetSessions(body: {
78
78
  amt?: number;
79
79
  query?: string;
80
+ known_ids?: string[];
81
+ unknown_ids?: string[];
82
+ active?: boolean;
83
+ user_id?: string;
80
84
  }): UseInfiniteQueryResult<InfiniteData<Session[], unknown>, StandardError>;
81
85
  useGetChats(body: {
82
86
  amt?: number;
@@ -928,6 +932,10 @@ export declare class AvroQueryClient {
928
932
  amt?: number;
929
933
  query?: string;
930
934
  offset?: number;
935
+ known_ids?: string[];
936
+ unknown_ids?: string[];
937
+ active?: boolean;
938
+ user_id?: string;
931
939
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
932
940
  private _initEmailListeners;
933
941
  trackEmail(options?: TrackEmailOptions): string;
@@ -805,7 +805,8 @@ export class AvroQueryClient {
805
805
  if (!this.companyId || this.companyId.trim() === '') {
806
806
  throw new StandardError(400, 'Company ID is required');
807
807
  }
808
- return this._fetch('POST', `/company/${this.companyId}/sessions`, JSON.stringify(body), cancelToken, {
808
+ const amount = body.amt ?? Math.max(body.unknown_ids?.length ?? 0, 50);
809
+ return this._fetch('POST', `/company/${this.companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
809
810
  ...headers,
810
811
  'Content-Type': 'application/json',
811
812
  })
@@ -1,62 +1,115 @@
1
1
  import { useMutation, useQuery, useInfiniteQuery } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../../client/QueryClient';
3
+ import { keys, isListKey } from '../../client/realtime';
4
+ import { Session } from '../../types/api';
5
+ const NS = 'sessions';
6
+ function listFilters(body) {
7
+ return {
8
+ query: body.query ?? '',
9
+ known_ids: body.known_ids ?? [],
10
+ unknown_ids: [...(body.unknown_ids ?? [])].sort(),
11
+ active: body.active ?? false,
12
+ user_id: body.user_id ?? null,
13
+ };
14
+ }
15
+ /** Apply `fn` to every cached sessions list (plain or paged), skipping empty caches. */
16
+ function patchSessionLists(qc, fn) {
17
+ qc.setQueriesData({ predicate: (q) => q.queryKey[0] === NS && isListKey(q.queryKey) }, (old) => {
18
+ if (!old)
19
+ return old;
20
+ if (Array.isArray(old))
21
+ return fn(old);
22
+ if (Array.isArray(old.pages)) {
23
+ return { ...old, pages: old.pages.map((p) => fn(p ?? [])) };
24
+ }
25
+ return old;
26
+ });
27
+ }
28
+ function snapshotSessionLists(qc) {
29
+ return qc.getQueriesData({
30
+ predicate: (q) => q.queryKey[0] === NS && isListKey(q.queryKey),
31
+ });
32
+ }
33
+ function restoreSessionLists(qc, snapshot) {
34
+ snapshot.forEach(([key, data]) => qc.setQueryData(key, data));
35
+ }
36
+ // ─── Reads ──────────────────────────────────────────────────────────
37
+ /** Paged company sessions (newest first). Filters become part of the list key. */
38
+ AvroQueryClient.prototype.useGetSessions = function (body = {}) {
39
+ const queryClient = this.getQueryClient();
40
+ const amt = body.amt ?? 50;
41
+ const result = useInfiniteQuery({
42
+ queryKey: keys.infinite(NS, this.companyId, listFilters(body)),
43
+ initialPageParam: 0,
44
+ getNextPageParam: (lastPage, allPages) => {
45
+ if (lastPage.length < amt)
46
+ return undefined;
47
+ return allPages.flat().length;
48
+ },
49
+ queryFn: ({ pageParam = 0 }) => this.fetchSessions({ ...body, amt, offset: pageParam }).then((sessions) => sessions.map((s) => new Session(s))),
50
+ enabled: Boolean(this.companyId),
51
+ });
52
+ if (result.data) {
53
+ result.data.pages.forEach((page) => {
54
+ page.forEach((session) => {
55
+ queryClient.setQueryData(keys.detail(NS, session.id), session);
56
+ });
57
+ });
58
+ }
59
+ return result;
60
+ };
61
+ /** The caller's own open sessions (any company). */
3
62
  AvroQueryClient.prototype.useGetUserSessions = function () {
4
- return useQuery({
5
- queryKey: ['sessions', this.companyId],
6
- queryFn: () => this.get({ path: '/session' }),
63
+ const queryClient = this.getQueryClient();
64
+ const result = useQuery({
65
+ queryKey: keys.list(NS, 'mine', { active: true }),
66
+ queryFn: () => this.get({ path: '/session' }).then((sessions) => (Array.isArray(sessions) ? sessions : []).map((s) => new Session(s))),
7
67
  enabled: Boolean(this.companyId),
8
68
  });
69
+ if (result.data) {
70
+ result.data.forEach((session) => {
71
+ queryClient.setQueryData(keys.detail(NS, session.id), session);
72
+ });
73
+ }
74
+ return result;
9
75
  };
76
+ /** Exactly the given sessions, in one request. */
10
77
  AvroQueryClient.prototype.useGetCompanySessionsByIds = function (sessionIds, params = {}) {
78
+ const queryClient = this.getQueryClient();
11
79
  const companyId = params.companyId ?? this.companyId;
12
80
  const sortedIds = [...sessionIds].sort();
13
- return useQuery({
14
- queryKey: ['sessions', companyId, 'by-ids', sortedIds],
15
- queryFn: async () => {
16
- const amount = Math.max(sortedIds.length, 50);
17
- const sessions = await this.post({
18
- path: `/company/${companyId}/sessions?amount=${amount}`,
19
- data: JSON.stringify({ unknown_ids: sortedIds }),
20
- headers: { 'Content-Type': 'application/json' },
21
- });
22
- return Array.isArray(sessions) ? sessions : [];
23
- },
81
+ const result = useQuery({
82
+ queryKey: keys.list(NS, companyId, listFilters({ unknown_ids: sortedIds })),
83
+ queryFn: () => this.fetchSessions({ unknown_ids: sortedIds, amt: sortedIds.length }).then((sessions) => sessions.map((s) => new Session(s))),
24
84
  enabled: Boolean(companyId) && sortedIds.length > 0 && (params.enabled ?? true),
25
85
  });
86
+ if (result.data) {
87
+ result.data.forEach((session) => {
88
+ queryClient.setQueryData(keys.detail(NS, session.id), session);
89
+ });
90
+ }
91
+ return result;
26
92
  };
93
+ /** Currently-open sessions across the company, in one request. */
27
94
  AvroQueryClient.prototype.useGetActiveCompanySessions = function (params = {}) {
95
+ const queryClient = this.getQueryClient();
28
96
  const companyId = params.companyId ?? this.companyId;
29
- return useQuery({
30
- queryKey: ['sessions', companyId, 'active'],
31
- queryFn: async () => {
32
- const pageSize = 100;
33
- const maxPages = 10;
34
- const knownIds = [];
35
- const openSessions = [];
36
- for (let page = 0; page < maxPages; page += 1) {
37
- const pageSessions = await this.post({
38
- path: `/company/${companyId}/sessions?amount=${pageSize}`,
39
- data: JSON.stringify({ known_ids: knownIds }),
40
- headers: { 'Content-Type': 'application/json' },
41
- });
42
- if (!Array.isArray(pageSessions) || pageSessions.length === 0)
43
- break;
44
- for (const session of pageSessions) {
45
- const isOpen = session.time_ended == null ||
46
- session.time_ended <= 0 ||
47
- session.time_ended < session.time_started;
48
- if (isOpen)
49
- openSessions.push(session);
50
- }
51
- knownIds.push(...pageSessions.map((s) => s.id).filter(Boolean));
52
- if (pageSessions.length < pageSize)
53
- break;
54
- }
55
- return openSessions;
56
- },
97
+ const result = useQuery({
98
+ queryKey: keys.list(NS, companyId, listFilters({ active: true })),
99
+ queryFn: () => this.fetchSessions({ active: true, amt: 500 }).then((sessions) => sessions.map((s) => new Session(s))),
57
100
  enabled: Boolean(companyId) && (params.enabled ?? true),
58
101
  });
102
+ if (result.data) {
103
+ result.data.forEach((session) => {
104
+ queryClient.setQueryData(keys.detail(NS, session.id), session);
105
+ });
106
+ }
107
+ return result;
59
108
  };
109
+ // ─── Mutations ──────────────────────────────────────────────────────
110
+ // Optimistic patch on every cached sessions list; the echoed `changes`
111
+ // batch settles the cache when the socket is up, else syncAfterMutation
112
+ // falls back to a refetch.
60
113
  AvroQueryClient.prototype.useCreateUserSession = function () {
61
114
  const queryClient = this.getQueryClient();
62
115
  return useMutation({
@@ -68,34 +121,22 @@ AvroQueryClient.prototype.useCreateUserSession = function () {
68
121
  });
69
122
  },
70
123
  onMutate: async ({ sessionData }) => {
71
- await queryClient.cancelQueries({
72
- queryKey: ['sessions', this.companyId],
73
- });
74
- const previousSessions = queryClient.getQueryData(['sessions', this.companyId]);
75
- queryClient.setQueryData(['sessions', this.companyId], (oldData) => {
76
- if (!oldData)
77
- return [];
78
- if (Array.isArray(oldData)) {
79
- return [
80
- ...oldData,
81
- {
82
- ...sessionData,
83
- id: Math.random().toString(36).substr(2, 9),
84
- company_id: this.companyId,
85
- },
86
- ];
87
- }
88
- return oldData;
124
+ await queryClient.cancelQueries({ queryKey: [NS] });
125
+ const previous = snapshotSessionLists(queryClient);
126
+ const optimistic = new Session({
127
+ ...sessionData,
128
+ id: `optimistic-${Math.random().toString(36).slice(2, 11)}`,
129
+ company_id: this.companyId,
89
130
  });
90
- return { previousSessions };
131
+ patchSessionLists(queryClient, (items) => [optimistic, ...items]);
132
+ return { previous };
91
133
  },
92
- onSuccess: () => {
93
- queryClient.invalidateQueries({ queryKey: ['sessions'] });
134
+ onError: (_err, _vars, context) => {
135
+ if (context?.previous)
136
+ restoreSessionLists(queryClient, context.previous);
94
137
  },
95
- onError: (err, variables, context) => {
96
- if (context?.previousSessions) {
97
- queryClient.setQueryData(['sessions', this.companyId], context.previousSessions);
98
- }
138
+ onSettled: () => {
139
+ this.syncAfterMutation('session', 'timecard');
99
140
  },
100
141
  });
101
142
  };
@@ -110,39 +151,29 @@ AvroQueryClient.prototype.useCreateSessionBreak = function () {
110
151
  });
111
152
  },
112
153
  onMutate: async ({ sessionId, breakData, }) => {
113
- await queryClient.cancelQueries({
114
- queryKey: ['sessions', this.companyId],
115
- });
116
- const previousSessions = queryClient.getQueryData(['sessions', this.companyId]);
117
- queryClient.setQueryData(['sessions', this.companyId], (oldData) => {
118
- if (!oldData)
119
- return oldData;
120
- if (Array.isArray(oldData)) {
121
- return oldData.map((session) => session.id === sessionId
122
- ? {
123
- ...session,
124
- breaks: [
125
- ...(session.breaks || []),
126
- {
127
- ...breakData,
128
- id: Math.random().toString(36).substr(2, 9),
129
- session_id: sessionId,
130
- },
131
- ],
132
- }
133
- : session);
134
- }
135
- return oldData;
136
- });
137
- return { previousSessions };
154
+ await queryClient.cancelQueries({ queryKey: [NS] });
155
+ const previous = snapshotSessionLists(queryClient);
156
+ patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId
157
+ ? new Session({
158
+ ...session,
159
+ breaks: [
160
+ ...(session.breaks || []),
161
+ {
162
+ ...breakData,
163
+ id: `optimistic-${Math.random().toString(36).slice(2, 11)}`,
164
+ session_id: sessionId,
165
+ },
166
+ ],
167
+ })
168
+ : session));
169
+ return { previous };
138
170
  },
139
- onSuccess: () => {
140
- queryClient.invalidateQueries({ queryKey: ['sessions'] });
171
+ onError: (_err, _vars, context) => {
172
+ if (context?.previous)
173
+ restoreSessionLists(queryClient, context.previous);
141
174
  },
142
- onError: (err, variables, context) => {
143
- if (context?.previousSessions) {
144
- queryClient.setQueryData(['sessions', this.companyId], context.previousSessions);
145
- }
175
+ onSettled: () => {
176
+ this.syncAfterMutation('session');
146
177
  },
147
178
  });
148
179
  };
@@ -157,27 +188,18 @@ AvroQueryClient.prototype.useUpdateUserSession = function () {
157
188
  });
158
189
  },
159
190
  onMutate: async ({ sessionId, updates, }) => {
160
- await queryClient.cancelQueries({
161
- queryKey: ['sessions', this.companyId],
162
- });
163
- const previousSessions = queryClient.getQueryData(['sessions', this.companyId]);
164
- queryClient.setQueryData(['sessions', this.companyId], (oldData) => {
165
- if (!oldData)
166
- return oldData;
167
- if (Array.isArray(oldData)) {
168
- return oldData.map((session) => session.id === sessionId ? { ...session, ...updates } : session);
169
- }
170
- return oldData;
171
- });
172
- return { previousSessions };
191
+ await queryClient.cancelQueries({ queryKey: [NS] });
192
+ const previous = snapshotSessionLists(queryClient);
193
+ patchSessionLists(queryClient, (items) => items.map((session) => session.id === sessionId ? new Session({ ...session, ...updates }) : session));
194
+ queryClient.setQueryData(keys.detail(NS, sessionId), (old) => old ? new Session({ ...old, ...updates }) : old);
195
+ return { previous };
173
196
  },
174
- onSuccess: () => {
175
- queryClient.invalidateQueries({ queryKey: ['sessions'] });
197
+ onError: (_err, _vars, context) => {
198
+ if (context?.previous)
199
+ restoreSessionLists(queryClient, context.previous);
176
200
  },
177
- onError: (err, variables, context) => {
178
- if (context?.previousSessions) {
179
- queryClient.setQueryData(['sessions', this.companyId], context.previousSessions);
180
- }
201
+ onSettled: () => {
202
+ this.syncAfterMutation('session', 'timecard');
181
203
  },
182
204
  });
183
205
  };
@@ -192,51 +214,20 @@ AvroQueryClient.prototype.useUpdateSessionBreak = function () {
192
214
  });
193
215
  },
194
216
  onMutate: async ({ breakId, updates }) => {
195
- await queryClient.cancelQueries({
196
- queryKey: ['sessions', this.companyId],
197
- });
198
- const previousSessions = queryClient.getQueryData(['sessions', this.companyId]);
199
- queryClient.setQueryData(['sessions', this.companyId], (oldData) => {
200
- if (!oldData)
201
- return oldData;
202
- if (Array.isArray(oldData)) {
203
- return oldData.map((session) => ({
204
- ...session,
205
- breaks: session.breaks?.map((b) => b.id === breakId ? { ...b, ...updates } : b),
206
- }));
207
- }
208
- return oldData;
209
- });
210
- return { previousSessions };
211
- },
212
- onSuccess: () => {
213
- queryClient.invalidateQueries({ queryKey: ['sessions'] });
217
+ await queryClient.cancelQueries({ queryKey: [NS] });
218
+ const previous = snapshotSessionLists(queryClient);
219
+ patchSessionLists(queryClient, (items) => items.map((session) => new Session({
220
+ ...session,
221
+ breaks: session.breaks?.map((b) => b.id === breakId ? { ...b, ...updates } : b),
222
+ })));
223
+ return { previous };
214
224
  },
215
- onError: (err, variables, context) => {
216
- if (context?.previousSessions) {
217
- queryClient.setQueryData(['sessions', this.companyId], context.previousSessions);
218
- }
225
+ onError: (_err, _vars, context) => {
226
+ if (context?.previous)
227
+ restoreSessionLists(queryClient, context.previous);
219
228
  },
220
- });
221
- };
222
- AvroQueryClient.prototype.useGetSessions = function (body) {
223
- const queryClient = this.getQueryClient();
224
- const result = useInfiniteQuery({
225
- queryKey: ['sessions', this.companyId, body.amt ?? 50, body.query ?? ''],
226
- initialPageParam: 0,
227
- getNextPageParam: (lastPage, allPages) => {
228
- if (lastPage.length < (body.amt ?? 50))
229
- return undefined;
230
- return allPages.flat().length; // next offset
229
+ onSettled: () => {
230
+ this.syncAfterMutation('session');
231
231
  },
232
- queryFn: ({ pageParam = 0 }) => this.fetchSessions({ ...body, offset: pageParam }),
233
232
  });
234
- if (result.data) {
235
- result.data.pages.forEach((data_page) => {
236
- data_page.forEach((session) => {
237
- queryClient.setQueryData(['session', session.id], session);
238
- });
239
- });
240
- }
241
- return result;
242
233
  };
@@ -55,6 +55,8 @@ export declare class ChangeApplier {
55
55
  apply(payload: ChangesPayload): void;
56
56
  private enqueue;
57
57
  flush(): Promise<void>;
58
+ /** True when some mounted hook is currently observing this namespace. */
59
+ private isObserved;
58
60
  private fetchAndApply;
59
61
  dispose(): void;
60
62
  }
@@ -4,7 +4,7 @@
4
4
  * `delete` removes, `invalidate` refetches. Query keys: `[ns, id]`
5
5
  * detail, `keys.list/keys.infinite(ns, scope, filters)` for lists.
6
6
  */
7
- import { constructEvent, Job, Route } from '../types/api';
7
+ import { constructEvent, Job, Route, Session } from '../types/api';
8
8
  export const keys = {
9
9
  detail: (ns, id) => [ns, id],
10
10
  list: (ns, scope, filters = {}) => [ns, 'list', scope ?? '', filters],
@@ -114,14 +114,22 @@ function matchBills(filters, item) {
114
114
  return 'unknown';
115
115
  return searchAware(filters);
116
116
  }
117
- function matchSessions(filters, item, _scope) {
118
- if (filters.scope === 'active')
119
- return item.time_ended ? 'nomatch' : 'match';
120
- if (filters.scope === 'mine')
117
+ function matchSessions(filters, item, scope) {
118
+ // "mine" comes from GET /session (viewer-scoped): can't tell ownership here.
119
+ if (scope === 'mine')
121
120
  return 'unknown';
122
- const byIds = withIds(filters, item);
123
- if (byIds)
124
- return byIds;
121
+ // `unknown_ids` on the sessions endpoint means "fetch exactly these".
122
+ const wanted = filters.unknown_ids;
123
+ if (Array.isArray(wanted) && wanted.length > 0) {
124
+ return wanted.includes(item.id) ? 'match' : 'nomatch';
125
+ }
126
+ const known = filters.known_ids;
127
+ if (Array.isArray(known) && known.length > 0 && known.includes(item.id))
128
+ return 'nomatch';
129
+ if (typeof filters.user_id === 'string' && item.user_id !== filters.user_id)
130
+ return 'nomatch';
131
+ if (filters.active === true && item.time_ended)
132
+ return 'nomatch';
125
133
  return searchAware(filters);
126
134
  }
127
135
  function matchCheckins(filters, item) {
@@ -199,11 +207,8 @@ export const REGISTRY = {
199
207
  bill: { ns: 'bills', fetchMany: bulk('fetchBills'), listMatch: matchBills },
200
208
  session: {
201
209
  ns: 'sessions',
202
- fetchMany: (client, ids) => client.post({
203
- path: `/company/${client.companyId}/sessions?amount=${ids.length}`,
204
- data: JSON.stringify({ unknown_ids: ids }),
205
- headers: { 'Content-Type': 'application/json' },
206
- }),
210
+ construct: (raw) => new Session(raw),
211
+ fetchMany: bulk('fetchSessions'),
207
212
  listMatch: matchSessions,
208
213
  alsoInvalidate: [['analytics', 'sessions']],
209
214
  },
@@ -362,10 +367,24 @@ export class ChangeApplier {
362
367
  this.pending.clear();
363
368
  await Promise.all(batches.map(([type, ids]) => this.fetchAndApply(type, [...ids])));
364
369
  }
370
+ /** True when some mounted hook is currently observing this namespace. */
371
+ isObserved(ns) {
372
+ return this.qc
373
+ .getQueryCache()
374
+ .findAll({ queryKey: [ns] })
375
+ .some((q) => q.getObserversCount() > 0);
376
+ }
365
377
  async fetchAndApply(type, ids) {
366
378
  const spec = REGISTRY[type];
367
379
  if (!spec)
368
380
  return;
381
+ // Nothing on screen needs this type: don't fetch on its behalf. Mark
382
+ // whatever is cached stale so the next mount refetches, and move on.
383
+ if (!this.isObserved(spec.ns)) {
384
+ ids.forEach((id) => this.qc.removeQueries({ queryKey: keys.detail(spec.ns, id) }));
385
+ invalidateType(this.qc, spec);
386
+ return;
387
+ }
369
388
  try {
370
389
  let raws = [];
371
390
  if (spec.fetchMany) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "0.1.0";
1
+ export declare const AVRO_JS_VERSION = "0.1.1";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // AUTO-GENERATED by scripts/gen-version.js — do not edit by hand.
2
2
  // Regenerated from package.json by the `prebuild` npm hook.
3
- export const AVRO_JS_VERSION = '0.1.0';
3
+ export const AVRO_JS_VERSION = '0.1.1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",