forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle-hooks.ts
More file actions
77 lines (72 loc) · 2.17 KB
/
Copy pathlifecycle-hooks.ts
File metadata and controls
77 lines (72 loc) · 2.17 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
import type { HttpResponse, HttpRequest } from './types';
/**
* Lifecycle hooks for the HTTP transport.
* Called at specific points during request processing.
*/
export interface RequestLifecycleHooks {
/**
* Called before the request is sent.
* Receives the resolved request object.
*/
beforeRequest?: (request: HttpRequest) => void | Promise<void>;
/**
* Called after a successful response (2xx).
* Receives the request and the response.
*/
afterResponse?: (request: HttpRequest, response: HttpResponse) => void | Promise<void>;
/**
* Called when an error occurs (non-2xx or network error).
* Receives the request and the error.
*/
onError?: (request: HttpRequest, error: Error) => void | Promise<void>;
/**
* Called when a retry is scheduled.
* Receives the request, attempt number, and delay in ms.
*/
onRetry?: (request: HttpRequest, attempt: number, delayMs: number) => void | Promise<void>;
}
/**
* Composes multiple lifecycle hook sets into one.
* Hooks are called in order. Errors in hooks are swallowed
* to prevent them from disrupting the request flow.
*/
export function composeHooks(...hookSets: RequestLifecycleHooks[]): RequestLifecycleHooks {
return {
async beforeRequest(request: HttpRequest) {
for (const hooks of hookSets) {
try {
await hooks.beforeRequest?.(request);
} catch {
// Swallow hook errors
}
}
},
async afterResponse(request: HttpRequest, response: HttpResponse) {
for (const hooks of hookSets) {
try {
await hooks.afterResponse?.(request, response);
} catch {
// Swallow hook errors
}
}
},
async onError(request: HttpRequest, error: Error) {
for (const hooks of hookSets) {
try {
await hooks.onError?.(request, error);
} catch {
// Swallow hook errors
}
}
},
async onRetry(request: HttpRequest, attempt: number, delayMs: number) {
for (const hooks of hookSets) {
try {
await hooks.onRetry?.(request, attempt, delayMs);
} catch {
// Swallow hook errors
}
}
},
};
}