forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase-client.ts
More file actions
68 lines (62 loc) · 2.05 KB
/
Copy pathbase-client.ts
File metadata and controls
68 lines (62 loc) · 2.05 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
import { LilyValidationError } from '../errors/sdk-error';
import type { HttpClient, HttpRequest } from '../http/types';
import type { ResolvedLilySdkConfig } from '../config/types';
import { createFetchHttpClient } from '../http/fetch-http-client';
export abstract class BaseClient {
protected readonly httpClient: HttpClient;
protected readonly config?: ResolvedLilySdkConfig;
public constructor(httpClientOrConfig: HttpClient | ResolvedLilySdkConfig) {
if (
'request' in httpClientOrConfig &&
typeof (httpClientOrConfig as HttpClient).request === 'function'
) {
this.httpClient = httpClientOrConfig as HttpClient;
} else {
const cfg = httpClientOrConfig as ResolvedLilySdkConfig;
this.config = cfg;
this.httpClient = createFetchHttpClient(cfg);
}
}
protected requireNonEmptyString(
value: unknown,
field: string,
): asserts value is string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new LilyValidationError(
`\`${field}\` must be a non-empty string.`,
{
code: 'VALIDATION_ERROR',
},
);
}
}
protected requireAtLeastOneNonEmptyString(
input: unknown,
fields: readonly string[],
): void {
if (
typeof input !== 'object' ||
input === null ||
!fields.some((field) => {
const value = (input as Record<string, unknown>)[field];
return typeof value === 'string' && value.trim().length > 0;
})
) {
throw new LilyValidationError(
`At least one of ${fields.map((field) => `\`${field}\``).join(', ')} must be a non-empty string.`,
{ code: 'VALIDATION_ERROR' },
);
}
}
protected buildPath(...segments: string[]): string {
return `/${segments.map((segment) => encodeURIComponent(segment)).join('/')}`;
}
public async request<TResponse, TRequest = undefined>(
request: HttpRequest<TRequest>,
): Promise<TResponse> {
const response = await this.httpClient.request<TResponse, TRequest>(
request,
);
return response.data;
}
}