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

request-log.ts

78 lines2.1 KB

1import { createStore, useStore } from "@/lib/store";
2​
3/**
4 * Every call to the fake API, for the request inspector. 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 /** The latency the fake network gave this request, in milliseconds. */
23 latencyMs: number;
24 /** Epoch milliseconds. */
25 startedAt: number;
26 endedAt: number | null;
27 durationMs: number | null;
29​
30/** The log keeps the most recent requests only. */
31export const REQUEST_LOG_LIMIT = 200;
32​
33export const requestLogStore = createStore<readonly RequestLogEntry[]>([]);
34​
35let nextId = 1;
36​
37export function logRequestStart(
38 request: Pick<RequestLogEntry, "method" | "url" | "requestBody" | "latencyMs">,
39 now = Date.now(),
40): number {
41 const id = nextId++;
42 const entry: RequestLogEntry = {
43 ...request,
44 id,
45 state: "pending",
46 status: null,
47 responseBody: null,
48 injectedFailure: false,
49 startedAt: now,
50 endedAt: null,
51 durationMs: null,
52 };
53 requestLogStore.set((entries) => [...entries, entry].slice(-REQUEST_LOG_LIMIT));
54 return id;
56​
57export function logRequestEnd(
58 id: number,
59 result: Pick<RequestLogEntry, "state" | "status" | "responseBody" | "injectedFailure">,
60 now = Date.now(),
61) {
62 requestLogStore.set((entries) =>
63 entries.map((entry) =>
64 entry.id === id
65 ? { ...entry, ...result, endedAt: now, durationMs: now - entry.startedAt }
66 : entry,
67 ),
68 );
70​
71export function clearRequestLog() {
72 requestLogStore.set([]);
74​
75/** Oldest first. */
76export function useRequestLog(): readonly RequestLogEntry[] {
77 return useStore(requestLogStore);