-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskmasterApi.ts
More file actions
491 lines (431 loc) · 16.1 KB
/
taskmasterApi.ts
File metadata and controls
491 lines (431 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import { getClient } from "../amplifyClient";
import type { ModelTaskListFilterInput, ModelSortDirection } from "../API";
import { getCurrentUserSub } from "../services/authIdentity";
import type {
CreateTaskInput,
CreateTaskListInput,
DeleteTaskInput,
DeleteTaskListInput,
CreateUserProfileInput,
UpdateUserProfileInput,
ModelUserProfileConditionInput,
ModelIntKeyConditionInput,
UpdateTaskInput,
UpdateTaskListInput,
} from "../API";
import {
createTaskListMinimal,
updateTaskListMinimal,
deleteTaskListMinimal,
listTaskListsMinimal,
listTaskListsAdminMinimal,
getTaskListMinimal,
createTaskMinimal,
updateTaskMinimal,
deleteTaskMinimal,
tasksByListMinimal,
tasksByListAdminMinimal,
getUserProfileMinimal,
getUserProfileEmailProbeMinimal,
createUserProfileMinimal,
updateUserProfileMinimal,
listUserProfilesMinimal,
listUserProfilesSafeMinimal,
// tasksByParentMinimal, // later if needed
} from "./operationsMinimal";
import type { ListTaskListsQuery, ListUserProfilesQuery, TasksByListQuery } from "../API";
import { TaskStatus } from "../API";
import { getInboxListId } from "../config/inboxSettings";
import { useUpdatesStore } from "../store/updatesStore";
function errorToMessage(err: unknown): string {
if (typeof err === "string") return err;
if (typeof err === "object" && err !== null) {
if ("errors" in err && Array.isArray((err as { errors?: unknown }).errors)) {
const errors = (err as { errors: Array<{ message?: unknown; errorType?: unknown }> }).errors;
const messages = errors
.map((e) => {
const msg = typeof e?.message === "string" ? e.message : "Unknown GraphQL error";
const type = typeof e?.errorType === "string" ? e.errorType : "";
return type ? `${msg} (${type})` : msg;
})
.filter(Boolean);
if (messages.length) return messages.join("; ");
}
if ("message" in err) return String((err as { message: unknown }).message);
}
return "Unknown error";
}
function shouldFallbackMissingIsDemo(err: unknown): boolean {
const msg = errorToMessage(err);
return msg.includes("Cannot return null for non-nullable type") && msg.includes("isDemo");
}
type TaskListItem = NonNullable<NonNullable<ListTaskListsQuery["listTaskLists"]>["items"]>[number];
type UserProfileItem = NonNullable<NonNullable<ListUserProfilesQuery["listUserProfiles"]>["items"]>[number];
type TaskItem = NonNullable<NonNullable<TasksByListQuery["tasksByList"]>["items"]>[number];
type CreateTaskListInputClient = Omit<CreateTaskListInput, "owner"> & { owner?: string };
type CreateTaskInputClient = Omit<CreateTaskInput, "owner"> & { owner?: string };
function stripOwnerField<T extends Record<string, unknown>>(input: T): Omit<T, "owner"> {
// Defense-in-depth: never allow client code to send `owner` in *update* mutation inputs.
// Ownership should not be transferable via client payloads.
const { owner: _owner, ...rest } = input as T & { owner?: unknown };
return rest;
}
// The operation documents in `operationsMinimal.ts` are typed as branded strings.
// Use those brands to infer variable + result types without any casts.
type GenQuery<I, O> = string & { __generatedQueryInput: I; __generatedQueryOutput: O };
type GenMutation<I, O> = string & { __generatedMutationInput: I; __generatedMutationOutput: O };
async function runQuery<I, O>(query: GenQuery<I, O>, variables: I): Promise<O> {
const client = getClient();
const res = await client.graphql<O, I>({ query, variables });
return res.data as O;
}
async function runMutation<I, O>(query: GenMutation<I, O>, variables: I): Promise<O> {
const client = getClient();
const res = await client.graphql<O, I>({ query, variables });
return res.data as O;
}
let ownerSubInFlight: Promise<string> | null = null;
let didLogOwnerSub = false;
async function getOwnerSub(): Promise<string> {
// Share a single in-flight lookup across concurrent createTask/createTaskList calls.
if (ownerSubInFlight) return ownerSubInFlight;
ownerSubInFlight = (async () => {
return await getCurrentUserSub();
})();
try {
const sub = await ownerSubInFlight;
if (import.meta.env.DEV && !didLogOwnerSub) {
didLogOwnerSub = true;
console.debug(`[taskmasterApi] resolved owner(sub)=${sub}`);
}
return sub;
} finally {
ownerSubInFlight = null;
}
}
/**
* Small helper for pagination if/when you need it.
*/
export type Page<T> = { items: T[]; nextToken?: string | null };
function toPage<T>(conn: { items?: (T | null)[] | null; nextToken?: string | null } | null | undefined): Page<T> {
return {
items: (conn?.items ?? []).filter(Boolean) as T[],
nextToken: conn?.nextToken ?? null,
};
}
/**
* API surface: keep it boring and predictable.
* Pages should call these methods instead of client.graphql directly.
*/
export const taskmasterApi = {
// -----------------------------
// UserProfile
// -----------------------------
async getUserProfile(id: string) {
const data = await runQuery(getUserProfileMinimal, { id });
return data.getUserProfile ?? null;
},
async getUserProfileEmailProbe(id: string) {
const data = await runQuery(getUserProfileEmailProbeMinimal, { id });
return data.getUserProfile ?? null;
},
async createUserProfile(input: CreateUserProfileInput) {
const data = await runMutation(createUserProfileMinimal, { input });
return data.createUserProfile;
},
async updateUserProfile(input: UpdateUserProfileInput, condition?: ModelUserProfileConditionInput | null) {
const data = await runMutation(updateUserProfileMinimal, {
input: stripOwnerField(input),
condition: condition ?? null,
});
return data.updateUserProfile;
},
async listUserProfiles(opts?: {
id?: string | null;
filter?: import("../API").ModelUserProfileFilterInput | null;
limit?: number;
nextToken?: string | null;
sortDirection?: import("../API").ModelSortDirection | null;
}): Promise<Page<UserProfileItem>> {
const data = await runQuery(listUserProfilesMinimal, {
id: opts?.id ?? null,
filter: opts?.filter ?? null,
sortDirection: opts?.sortDirection ?? null,
limit: opts?.limit ?? 50,
nextToken: opts?.nextToken ?? null,
});
const conn = data.listUserProfiles;
return toPage<UserProfileItem>(conn);
},
async listUserProfilesSafe(opts?: {
id?: string | null;
filter?: import("../API").ModelUserProfileFilterInput | null;
limit?: number;
nextToken?: string | null;
sortDirection?: import("../API").ModelSortDirection | null;
}): Promise<Page<UserProfileItem>> {
const data = await runQuery(listUserProfilesSafeMinimal, {
id: opts?.id ?? null,
filter: opts?.filter ?? null,
sortDirection: opts?.sortDirection ?? null,
limit: opts?.limit ?? 50,
nextToken: opts?.nextToken ?? null,
});
const conn = data.listUserProfiles;
return toPage<UserProfileItem>(conn);
},
// -----------------------------
// TaskLists
// -----------------------------
async listTaskLists(opts?: {
id?: string | null;
filter?: ModelTaskListFilterInput | null;
limit?: number;
nextToken?: string | null;
sortDirection?: ModelSortDirection | null;
}): Promise<Page<TaskListItem>> {
// Prefer including `isDemo` so the normal UI can accurately mark demo data.
// If legacy records are missing the now-required `isDemo`, fall back to a safe query
// that omits it (otherwise the whole query can hard-fail).
let data: unknown;
try {
data = await runQuery(listTaskListsAdminMinimal, {
id: opts?.id ?? null,
filter: opts?.filter ?? null,
sortDirection: opts?.sortDirection ?? null,
limit: opts?.limit ?? 50,
nextToken: opts?.nextToken ?? null,
});
} catch (err) {
if (!shouldFallbackMissingIsDemo(err)) throw err;
data = await runQuery(listTaskListsMinimal, {
id: opts?.id ?? null,
filter: opts?.filter ?? null,
sortDirection: opts?.sortDirection ?? null,
limit: opts?.limit ?? 50,
nextToken: opts?.nextToken ?? null,
});
}
const conn = (data as ListTaskListsQuery).listTaskLists;
return toPage<TaskListItem>(conn);
},
// Admin-only: includes `isDemo` in selection set.
async listTaskListsAdmin(opts?: {
id?: string | null;
filter?: ModelTaskListFilterInput | null;
limit?: number;
nextToken?: string | null;
sortDirection?: ModelSortDirection | null;
}): Promise<Page<TaskListItem>> {
const data = await runQuery(listTaskListsAdminMinimal, {
id: opts?.id ?? null,
filter: opts?.filter ?? null,
sortDirection: opts?.sortDirection ?? null,
limit: opts?.limit ?? 50,
nextToken: opts?.nextToken ?? null,
});
const conn = data.listTaskLists;
return toPage<TaskListItem>(conn);
},
async listTaskListsOwned(opts?: {
limit?: number;
nextToken?: string | null;
ownerSub?: string;
}): Promise<Page<TaskListItem>> {
const owner = opts?.ownerSub ?? (await getOwnerSub());
return await this.listTaskLists({
limit: opts?.limit,
nextToken: opts?.nextToken,
filter: { owner: { eq: owner } },
});
},
async listTaskListsOwnedAdmin(opts?: {
limit?: number;
nextToken?: string | null;
ownerSub?: string;
}): Promise<Page<TaskListItem>> {
const owner = opts?.ownerSub ?? (await getOwnerSub());
return await this.listTaskListsAdmin({
limit: opts?.limit,
nextToken: opts?.nextToken,
filter: { owner: { eq: owner } },
});
},
async getTaskList(id: string) {
const data = await runQuery(getTaskListMinimal, { id });
return data.getTaskList ?? null;
},
async createTaskList(input: CreateTaskListInputClient) {
const owner = input.owner ?? (await getOwnerSub());
const data = await runMutation(createTaskListMinimal, { input: { ...input, owner } });
return data.createTaskList;
},
async updateTaskList(input: UpdateTaskListInput) {
const data = await runMutation(updateTaskListMinimal, { input: stripOwnerField(input) });
return data.updateTaskList;
},
async deleteTaskList(input: DeleteTaskListInput) {
const data = await runMutation(deleteTaskListMinimal, { input });
return data.deleteTaskList;
},
async deleteTaskListSafeById(listId: string) {
const inboxId = getInboxListId();
if (inboxId && listId === inboxId) return;
return await this.deleteTaskList({ id: listId });
},
// -----------------------------
// Tasks
// -----------------------------
async tasksByList(opts: {
listId: string;
sortOrder?: ModelIntKeyConditionInput;
sortDirection?: ModelSortDirection;
limit?: number;
nextToken?: string | null;
}): Promise<Page<TaskItem>> {
// Prefer including `isDemo` so the normal UI can accurately mark demo tasks.
// If legacy records are missing the now-required `isDemo`, fall back to a safe query
// that omits it (otherwise the whole query can hard-fail).
let data: unknown;
try {
data = await runQuery(tasksByListAdminMinimal, {
listId: opts.listId,
sortOrder: opts.sortOrder ?? { ge: 0 },
sortDirection: opts.sortDirection,
limit: opts.limit ?? 200,
nextToken: opts.nextToken ?? null,
});
} catch (err) {
if (!shouldFallbackMissingIsDemo(err)) throw err;
data = await runQuery(tasksByListMinimal, {
listId: opts.listId,
sortOrder: opts.sortOrder ?? { ge: 0 },
sortDirection: opts.sortDirection,
limit: opts.limit ?? 200,
nextToken: opts.nextToken ?? null,
});
}
const conn = (data as TasksByListQuery).tasksByList;
return toPage<TaskItem>(conn);
},
// Admin-only: includes `isDemo` in selection set.
async tasksByListAdmin(opts: {
listId: string;
sortOrder?: ModelIntKeyConditionInput;
sortDirection?: ModelSortDirection;
limit?: number;
nextToken?: string | null;
}): Promise<Page<TaskItem>> {
const data = await runQuery(tasksByListAdminMinimal, {
listId: opts.listId,
sortOrder: opts.sortOrder ?? { ge: 0 },
sortDirection: opts.sortDirection,
limit: opts.limit ?? 200,
nextToken: opts.nextToken ?? null,
});
const conn = data.tasksByList;
return toPage<TaskItem>(conn);
},
async createTask(input: CreateTaskInputClient) {
const owner = input.owner ?? (await getOwnerSub());
const data = await runMutation(createTaskMinimal, { input: { ...input, owner } });
const created = data.createTask;
if (created?.id && created?.listId) {
useUpdatesStore.getState().addEvent({
type: "task_created",
taskId: created.id,
listId: created.listId,
title: `Task created: ${created.title ?? "(untitled)"}`,
parentTaskId: created.parentTaskId ?? null,
});
}
return created;
},
async updateTask(input: UpdateTaskInput) {
const data = await runMutation(updateTaskMinimal, { input: stripOwnerField(input) });
const updated = data.updateTask;
if (updated?.id && updated?.listId) {
const hasOwn = (k: keyof UpdateTaskInput) => Object.prototype.hasOwnProperty.call(input, k);
// Many UI “edit task” forms submit status + completedAt even when status didn’t change.
// So we only emit completed/reopened when the update appears to be status-only.
const hasContentFields =
hasOwn("title") ||
hasOwn("description") ||
hasOwn("priority") ||
hasOwn("dueAt") ||
hasOwn("assigneeId") ||
hasOwn("tagIds");
const hasMoveFields = hasOwn("listId") || hasOwn("parentTaskId") || hasOwn("sortOrder");
const isStatusOnly = hasOwn("status") && !hasContentFields && !hasMoveFields;
const isMoveOnly = !hasOwn("status") && hasMoveFields && !hasContentFields;
const type: "task_completed" | "task_reopened" | "task_updated" = isStatusOnly
? input.status === TaskStatus.Done
? "task_completed"
: input.status === TaskStatus.Open
? "task_reopened"
: "task_updated"
: "task_updated";
const prefix = isMoveOnly ? "Task moved" : type === "task_completed"
? "Task completed"
: type === "task_reopened"
? "Task reopened"
: "Task updated";
useUpdatesStore.getState().addEvent({
type,
taskId: updated.id,
listId: updated.listId,
title: `${prefix}: ${updated.title ?? "(untitled)"}`,
parentTaskId: updated.parentTaskId ?? null,
});
}
return updated;
},
async deleteTask(input: DeleteTaskInput) {
const data = await runMutation(deleteTaskMinimal, { input });
const deleted = data.deleteTask;
// Note: delete mutation selection set must include listId/title for this to be informative.
if (deleted?.id && deleted?.listId) {
useUpdatesStore.getState().addEvent({
type: "task_deleted",
taskId: deleted.id,
listId: deleted.listId,
title: `Task deleted: ${deleted.title ?? "(untitled)"}`,
parentTaskId: deleted.parentTaskId ?? null,
});
} else if (input?.id) {
// Fallback: still record something, even if the mutation didn't return enough data.
useUpdatesStore.getState().addEvent({
type: "task_deleted",
taskId: input.id,
listId: "unknown",
title: "Task deleted",
parentTaskId: null,
});
}
return deleted;
},
async setTaskStatus(taskId: string, status: TaskStatus ) {
const now = new Date().toISOString();
return await this.updateTask({
id: taskId,
status,
completedAt: status === TaskStatus.Done ? now : null,
});
},
// -----------------------------
// Helpers
// -----------------------------
async moveTaskToList(taskId: string, targetListId: string, opts?: { sortOrder?: number }) {
return await this.updateTask({
id: taskId,
listId: targetListId,
parentTaskId: null,
sortOrder: opts?.sortOrder ?? 0, // see note below
});
},
async sendTaskToInbox(taskId: string) {
const inboxId = getInboxListId();
if (!inboxId) return;
return await this.moveTaskToList(taskId, inboxId);
},
};