File size: 3,591 Bytes
ea2c336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------
// alerts/alertsApi.ts β€” WAVE 20 item 25 (C-ALERT): the seven calls, and nothing
// else. Every one carries the session cookie and fails CLOSED: an unreadable
// answer is an empty inbox, never a half-parsed one.
//
// Shaped like `shell/session.ts` on purpose β€” the same `{ok}` result type, the
// same 4xx/5xx message policy β€” because the failure that matters is identical:
// a wrong `credentials` word produces no client-side symptom at all, just a 401
// from a server that never saw a session.
// ---------------------------------------------------------------------------

import { API_V1, CREDENTIALS } from "../apiContract";
import { EMPTY_INBOX, parseAlerts, parseInbox } from "./alertsModel";
import type { Alert, Inbox } from "./alertsModel";

export type Result<T> =
  | { ok: true; value: T }
  | { ok: false; status: number; message: string };

/** 4xx text is POLICY the reader needs ("this view has no filter"); a 5xx's text
 *  is the server's internals and is never shown. Same split as session.ts. */
export function errorMessage(status: number, message?: string): string {
  if (status >= 500 || !message) {
    return status >= 500
      ? "Something went wrong on our side. Try again in a moment."
      : `The server answered ${status}.`;
  }
  return message;
}

async function call<T>(
  path: string,
  init: RequestInit,
  read: (body: unknown) => T
): Promise<Result<T>> {
  let res: Response;
  try {
    res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
  } catch {
    return { ok: false, status: 0, message: "Cannot reach the server." };
  }
  const body = (await res.json().catch(() => null)) as unknown;
  if (!res.ok) {
    const detail = (body as { error?: { message?: string } } | null)?.error?.message;
    return { ok: false, status: res.status, message: errorMessage(res.status, detail) };
  }
  return { ok: true, value: read(body) };
}

const json = (data: unknown): RequestInit => ({
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(data),
});

export function fetchInbox(): Promise<Result<Inbox>> {
  return call("/notifications", {}, parseInbox);
}

/** `ids: null` marks EVERYTHING β€” the API's own convention, not a shortcut. */
export function markRead(ids: string[] | null, read = true): Promise<Result<true>> {
  return call("/notifications/read", json({ ids, read }), () => true as const);
}

export function fetchAlerts(): Promise<Result<Alert[]>> {
  return call("/alerts", {}, parseAlerts);
}

/**
 * `POST /alerts`. ⚠ 400 `no_filter` is a REAL ANSWER, not a failure to handle:
 * a view with no active filter matches every row, so an alert on it would seed
 * with the whole table and could never see an entrant again. The message rides
 * back to the caller verbatim β€” that is the difference between "refused" and
 * "silently incapable".
 */
export function createAlert(
  viewId: string,
  topic: string,
  label?: string
): Promise<Result<unknown>> {
  return call("/alerts", json({ viewId, topic, ...(label ? { label } : {}) }), (b) => b);
}

export function deleteAlert(id: string): Promise<Result<true>> {
  return call(`/alerts/${encodeURIComponent(id)}`, { method: "DELETE" }, () => true as const);
}

/** Run one alert now. Answers `{new:[rowId], seeded}` or `{skipped:"<reason>"}`. */
export function runAlert(id: string): Promise<Result<unknown>> {
  return call(`/alerts/${encodeURIComponent(id)}/run`, { method: "POST" }, (b) => b);
}

export { EMPTY_INBOX };