-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiKeyHttpClient.ts
More file actions
97 lines (81 loc) · 2.41 KB
/
ApiKeyHttpClient.ts
File metadata and controls
97 lines (81 loc) · 2.41 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
88
89
90
91
92
93
94
95
96
97
import { HttpClient } from './HttpClient';
import { AuthenticationError } from './errors';
export class ApiKeyHttpClient extends HttpClient {
private apiKey: string;
private headerName: string;
private headerPrefix: string;
private isAuth: boolean = false;
constructor(
baseUrl: string,
apiKey: string,
headerName: string = 'X-API-Key',
headerPrefix: string = '',
timeout?: number,
cacheConfig?: {
enabled?: boolean;
ttl?: number;
respectCacheHeaders?: boolean;
maxSize?: number;
}
) {
super(baseUrl, timeout, 3, 1000, cacheConfig);
this.apiKey = apiKey;
this.headerName = headerName;
this.headerPrefix = headerPrefix;
}
async authenticate(): Promise<void> {
if (!this.apiKey) {
throw new AuthenticationError('API key is required');
}
try {
await this.get('/user');
this.isAuth = true;
} catch (error) {
this.isAuth = false;
if (error instanceof Error) {
throw new AuthenticationError(`API key validation failed: ${error.message}`);
}
throw new AuthenticationError('API key validation failed with unknown error');
}
}
isAuthenticated(): boolean {
return this.isAuth && !!this.apiKey;
}
getAuthHeaders(): Record<string, string> {
if (!this.apiKey) {
return {};
}
const headerValue = this.headerPrefix ? `${this.headerPrefix} ${this.apiKey}` : this.apiKey;
return {
[this.headerName]: headerValue,
};
}
public setApiKey(apiKey: string): void {
this.apiKey = apiKey;
this.isAuth = false;
}
public setHeaderName(headerName: string): void {
this.headerName = headerName;
}
public setHeaderPrefix(headerPrefix: string): void {
this.headerPrefix = headerPrefix;
}
public getApiKey(): string {
return this.apiKey;
}
public getAccessToken(): string | null {
return this.apiKey || null;
}
public getHeaderName(): string {
return this.headerName;
}
public getHeaderPrefix(): string {
return this.headerPrefix;
}
public static createGitLabTokenClient(baseUrl: string, token: string, timeout?: number): ApiKeyHttpClient {
return new ApiKeyHttpClient(baseUrl, token, 'Authorization', 'Bearer', timeout);
}
public static createGenericTokenClient(baseUrl: string, token: string, timeout?: number): ApiKeyHttpClient {
return new ApiKeyHttpClient(baseUrl, token, 'X-API-Key', '', timeout);
}
}