23 lines
1.3 KiB
TypeScript
23 lines
1.3 KiB
TypeScript
import type { KyInstance } from "ky";
|
|
import { listMessages } from "../message/tools.js";
|
|
import { listTasks } from "../task/tools.js";
|
|
import { EventStore } from "./store.js";
|
|
import type { EventPollResult, EventRecord } from "./types.js";
|
|
|
|
function eventId(kind: EventRecord["kind"], id: string, updatedAt?: number): string { return `${kind}:${id}:${updatedAt ?? 0}`; }
|
|
|
|
export async function pollEvents(client: KyInstance, corpId: string, store: EventStore, count = 50): Promise<EventPollResult> {
|
|
const observedAt = Date.now();
|
|
const [todo, messages] = await Promise.all([
|
|
listTasks(client, corpId, "todo", { start: 0, count }),
|
|
listMessages(client, corpId, { start: 0, count, read: false }),
|
|
]);
|
|
const candidates: EventRecord[] = [
|
|
...todo.items.map((payload) => ({ id: eventId("todo", payload.taskId, payload.updatedAt || payload.actionTime), kind: "todo" as const, corpId, observedAt, payload })),
|
|
...messages.items.map((payload) => ({ id: eventId("message", payload.id, payload.updateTime || payload.createTime), kind: "message" as const, corpId, observedAt, payload })),
|
|
];
|
|
const newEvents = candidates.filter((event) => !store.has(event.id));
|
|
store.commit(candidates);
|
|
return { corpId, observedAt, scanned: { todo: todo.items.length, messages: messages.items.length }, newEvents, duplicateCount: candidates.length - newEvents.length };
|
|
}
|