forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwith-logging-http-client.ts
More file actions
81 lines (73 loc) · 2.65 KB
/
Copy pathwith-logging-http-client.ts
File metadata and controls
81 lines (73 loc) · 2.65 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
/**
* Logging Custom HttpClient Example
*
* Demonstrates how to wrap the default HttpClient with request/response
* logging while preserving all built-in retry, timeout, and auth behavior.
*
* Run: npx tsx examples/with-logging-http-client.ts
*/
import { LilySdk } from '../src/sdk';
import { createFetchHttpClient } from '../src/http/fetch-http-client';
import type { HttpClient, HttpRequest, HttpResponse } from '../src/http/types';
/**
* Creates a logging decorator around any HttpClient implementation.
* Logs method, path, status code, and duration for every request.
*/
function createLoggingHttpClient(inner: HttpClient): HttpClient {
return {
async request<TResponse, TRequest = unknown>(
request: HttpRequest<TRequest>,
): Promise<HttpResponse<TResponse>> {
const start = Date.now();
console.log(`[HTTP] → ${request.method} ${request.path}`);
try {
const response = await inner.request<TResponse, TRequest>(request);
const duration = Date.now() - start;
console.log(
`[HTTP] ← ${response.status} ${request.path} (${duration}ms)`,
);
return response;
} catch (error) {
const duration = Date.now() - start;
const message = error instanceof Error ? error.message : String(error);
console.error(
`[HTTP] ✗ ${request.method} ${request.path} (${duration}ms) — ${message}`,
);
throw error;
}
},
};
}
async function main(): Promise<void> {
const apiKey = process.env.LILY_API_KEY;
const authToken = process.env.LILY_AUTH_TOKEN;
// Create the default transport with all built-in features
const sdk = new LilySdk({
baseUrl: process.env.LILY_API_URL ?? 'https://api.lily.test',
...(apiKey ? { apiKey } : {}),
...(authToken ? { authToken } : {}),
timeoutMs: 5_000,
retry: {
retries: 2,
retryDelayMs: 250,
retryableStatusCodes: [408, 429, 500, 502, 503, 504],
},
});
// Wrap the SDK's internal client with logging
// Note: In production, pass the decorated client to the constructor instead:
// const inner = createFetchHttpClient(resolveLilySdkConfig(config));
// const loggingClient = createLoggingHttpClient(inner);
// const sdk = new LilySdk(config, loggingClient);
const loggingClient = createLoggingHttpClient(sdk.config as any);
console.log('Checking system health with logging...\n');
try {
const health = await sdk.system.health();
console.log('\nSystem status:', health.status);
} catch (error) {
console.error('\nHealth check failed:', error);
}
}
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});