Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

request-log.ts

76 lines2.1 KB

1import { createStore, useStore } from "@/lib/store";
2​
3/**
4 * Every call to the fake API, for the request inspector (phase 4). An entry
5 * is added when the request starts (`pending`) and completed when it settles,
6 * so slow requests show up while they're in flight.
7 */
8export interface RequestLogEntry {
9 id: number;
10 method: string;
11 /** Path and query, e.g. `/api/notes/note-01`. */
12 url: string;
13 state: "pending" | "done" | "aborted";
14 /** HTTP status, once there's a response. */
15 status: number | null;
16 /** Request body, parsed from JSON. */
17 requestBody: unknown;
18 /** Response body, parsed from JSON (`null` for empty responses). */
19 responseBody: unknown;
20 /** The failure came from failure injection, not from the server's own rules. */
21 injectedFailure: boolean;
22 /** Epoch milliseconds. */
23 startedAt: number;
24 endedAt: number | null;
25 durationMs: number | null;
27​
28/** The log keeps the most recent requests only. */
29export const REQUEST_LOG_LIMIT = 200;
30​
31export const requestLogStore = createStore<readonly RequestLogEntry[]>([]);
32​
33let nextId = 1;
34​
35export function logRequestStart(
36 request: Pick<RequestLogEntry, "method" | "url" | "requestBody">,
37 now = Date.now(),
38): number {
39 const id = nextId++;
40 const entry: RequestLogEntry = {
41 ...request,
42 id,
43 state: "pending",
44 status: null,
45 responseBody: null,
46 injectedFailure: false,
47 startedAt: now,
48 endedAt: null,
49 durationMs: null,
50 };
51 requestLogStore.set((entries) => [...entries, entry].slice(-REQUEST_LOG_LIMIT));
52 return id;
54​
55export function logRequestEnd(
56 id: number,
57 result: Pick<RequestLogEntry, "state" | "status" | "responseBody" | "injectedFailure">,
58 now = Date.now(),
59) {
60 requestLogStore.set((entries) =>
61 entries.map((entry) =>
62 entry.id === id
63 ? { ...entry, ...result, endedAt: now, durationMs: now - entry.startedAt }
64 : entry,
65 ),
66 );
68​
69export function clearRequestLog() {
70 requestLogStore.set([]);
72​
73/** Oldest first. */
74export function useRequestLog(): readonly RequestLogEntry[] {
75 return useStore(requestLogStore);