forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
87 lines (75 loc) · 2.06 KB
/
Copy pathclient.ts
File metadata and controls
87 lines (75 loc) · 2.06 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
import { isLilyApiError, LilyApiError } from "./errors";
interface ErrorPayload {
code?: unknown;
message?: unknown;
details?: unknown;
}
async function readErrorPayload(response: Response): Promise<ErrorPayload> {
const contentType = response.headers.get("content-type") ?? "";
if (contentType.includes("application/json")) {
try {
const payload: unknown = await response.json();
return typeof payload === "object" && payload !== null
? (payload as ErrorPayload)
: { details: payload };
} catch {
return {};
}
}
try {
const message = await response.text();
return message ? { message } : {};
} catch {
return {};
}
}
/**
* Fetches a Lily API resource and normalizes transport and HTTP failures.
* Network failures use status `0` and code `NETWORK_ERROR`.
*/
export async function lilyFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
let response: Response;
try {
response = await fetch(input, init);
} catch (error) {
throw new LilyApiError({
status: 0,
code: "NETWORK_ERROR",
message: "Unable to reach the Lily API.",
details:
error instanceof Error
? { cause: error.message }
: { cause: "Unknown network error" },
});
}
if (response.ok) {
return response;
}
const payload = await readErrorPayload(response);
throw new LilyApiError({
status: response.status,
code:
typeof payload.code === "string"
? payload.code
: `HTTP_${response.status}`,
message:
typeof payload.message === "string"
? payload.message
: response.statusText || "Lily API request failed.",
details: payload.details,
});
}
/** Converts an unknown thrown value into the shared API error model. */
export function toLilyApiError(error: unknown): LilyApiError {
if (isLilyApiError(error)) {
return error;
}
return new LilyApiError({
status: 0,
code: "UNKNOWN_ERROR",
message: error instanceof Error ? error.message : "An unknown error occurred.",
});
}