-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapiClient.ts
More file actions
403 lines (360 loc) · 11.2 KB
/
Copy pathapiClient.ts
File metadata and controls
403 lines (360 loc) · 11.2 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios';
import { pathToSlug, slugToPath } from './lib/url';
import type { ValidationResult, ReloadResult } from './lib/types';
/**
* Configuration options for FlapiApiClient
*/
export interface FlapiApiClientOptions {
baseURL: string;
token?: string;
debug?: boolean;
timeout?: number;
}
/**
* Response from /by-template endpoint
*/
export interface EndpointTemplateMatch {
url_path?: string;
method?: string;
config_file_path: string;
template_source: string;
type: 'REST' | 'MCP_Tool' | 'MCP_Resource' | 'MCP_Prompt';
mcp_name?: string;
full_config?: any; // Full endpoint configuration
}
export interface FindByTemplateResponse {
template_path: string;
count: number;
endpoints: EndpointTemplateMatch[];
}
export interface ParameterDefinition {
name: string;
in: string;
description?: string;
required: boolean;
default?: string;
validators?: Array<{
type: string;
min?: number;
max?: number;
regex?: string;
allowedValues?: string[];
}>;
}
export interface GetParametersResponse {
endpoint: string;
method: string;
parameters: ParameterDefinition[];
}
export interface EnvironmentVariable {
name: string;
value?: string;
available: boolean;
}
export interface GetEnvironmentVariablesResponse {
variables: EnvironmentVariable[];
}
export interface LogLevelResponse {
level: 'debug' | 'info' | 'warning' | 'error';
message?: string;
}
/**
* Centralized API client for Flapi config service
*
* Features:
* - Automatic authentication
* - Request/response logging
* - Typed API methods
* - Consistent error handling
* - Path/slug conversion utilities
*/
export class FlapiApiClient {
private client: AxiosInstance;
private debug: boolean;
constructor(options: FlapiApiClientOptions) {
this.debug = options.debug ?? false;
const headers: Record<string, string> = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
// For config service endpoints, send both X-Config-Token and Authorization headers
if (options.token) {
headers['X-Config-Token'] = options.token;
headers['Authorization'] = `Bearer ${options.token}`;
}
this.client = axios.create({
baseURL: options.baseURL,
timeout: options.timeout ?? 30000,
headers
});
this.setupInterceptors();
}
/**
* Setup request/response interceptors for logging and error handling
*/
private setupInterceptors() {
// Request interceptor
this.client.interceptors.request.use(
(config) => {
if (this.debug) {
const timestamp = new Date().toISOString();
console.log(`[FlapiAPI] ${timestamp} → ${config.method?.toUpperCase()} ${config.url}`);
if (config.headers) {
const sanitized = this.sanitizeHeaders(config.headers);
console.log('[FlapiAPI] Headers:', JSON.stringify(sanitized, null, 2));
}
if (config.data) {
const dataStr = JSON.stringify(config.data);
const preview = dataStr.length > 500 ? dataStr.substring(0, 500) + '...' : dataStr;
console.log('[FlapiAPI] Body:', preview);
}
}
return config;
},
(error) => {
if (this.debug) {
console.error('[FlapiAPI] ✗ Request error:', error.message);
}
return Promise.reject(error);
}
);
// Response interceptor
this.client.interceptors.response.use(
(response) => {
if (this.debug) {
const timestamp = new Date().toISOString();
const dataSize = JSON.stringify(response.data).length;
console.log(`[FlapiAPI] ${timestamp} ← ${response.status} ${response.config.url}`);
console.log(`[FlapiAPI] Size: ${dataSize} bytes`);
if (dataSize < 1000) {
console.log('[FlapiAPI] Data:', JSON.stringify(response.data, null, 2));
}
}
return response;
},
(error) => {
if (this.debug) {
const timestamp = new Date().toISOString();
console.error(`[FlapiAPI] ${timestamp} ✗ ${error.response?.status || 'ERROR'} ${error.config?.url}`);
console.error('[FlapiAPI] Error:', error.message);
if (error.response?.data) {
console.error('[FlapiAPI] Response:', JSON.stringify(error.response.data, null, 2));
}
}
return Promise.reject(error);
}
);
}
/**
* Sanitize headers for logging (hide sensitive data)
*/
private sanitizeHeaders(headers: any): any {
const copy = { ...headers };
if (copy.Authorization) {
const parts = copy.Authorization.split(' ');
if (parts.length === 2) {
const token = parts[1];
copy.Authorization = `${parts[0]} ${token.substring(0, 3)}***${token.substring(token.length - 4)}`;
}
}
if (copy['X-Config-Token']) {
const token = copy['X-Config-Token'];
copy['X-Config-Token'] = `${token.substring(0, 3)}***${token.substring(token.length - 4)}`;
}
return copy;
}
/**
* Update authentication token
*/
setToken(token: string | undefined) {
if (token) {
this.client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
this.client.defaults.headers.common['X-Config-Token'] = token;
} else {
delete this.client.defaults.headers.common['Authorization'];
delete this.client.defaults.headers.common['X-Config-Token'];
}
if (this.debug) {
console.log('[FlapiAPI] Token updated');
}
}
/**
* Enable/disable debug logging
*/
enableDebug(enable = true) {
this.debug = enable;
if (this.debug) {
console.log('[FlapiAPI] Debug logging enabled');
}
}
/**
* Get raw axios client for custom requests
*/
getRawClient(): AxiosInstance {
return this.client;
}
// ============================================================================
// Typed API Methods
// ============================================================================
/**
* Find all endpoints that reference a specific SQL template file
*/
async findEndpointsByTemplate(templatePath: string): Promise<FindByTemplateResponse> {
const response = await this.client.post<FindByTemplateResponse>(
'/api/v1/_config/endpoints/by-template',
{ template_path: templatePath }
);
return response.data;
}
/**
* Get endpoint configuration by URL path
* Automatically converts path to slug
*/
async getEndpointByPath(path: string): Promise<any> {
const slug = pathToSlug(path);
const response = await this.client.get(`/api/v1/_config/endpoints/${slug}`);
return response.data;
}
/**
* Get endpoint configuration by MCP name
*/
async getEndpointByMcpName(name: string): Promise<any> {
const response = await this.client.get(`/api/v1/_config/endpoints/${name}`);
return response.data;
}
/**
* Get parameter definitions for an endpoint
*/
async getEndpointParameters(pathOrName: string): Promise<GetParametersResponse> {
const slug = pathToSlug(pathOrName);
const response = await this.client.get<GetParametersResponse>(
`/api/v1/_config/endpoints/${slug}/parameters`
);
return response.data;
}
/**
* Test an endpoint with given parameters.
* Targets the server's `/template/test` route (the only test route that exists;
* see src/config_service.cpp).
*/
async testEndpoint(pathOrName: string, parameters: Record<string, any>): Promise<any> {
const slug = pathToSlug(pathOrName);
const response = await this.client.post(
`/api/v1/_config/endpoints/${slug}/template/test`,
{ parameters }
);
return response.data;
}
/**
* Get available environment variables
*/
async getEnvironmentVariables(): Promise<GetEnvironmentVariablesResponse> {
const response = await this.client.get<GetEnvironmentVariablesResponse>(
'/api/v1/_config/environment-variables'
);
return response.data;
}
/**
* Get filesystem structure
*/
async getFilesystem(): Promise<any> {
const response = await this.client.get('/api/v1/_config/filesystem');
return response.data;
}
/**
* Get schema information
*/
async getSchema(format?: 'completion'): Promise<any> {
const url = format
? `/api/v1/_config/schema?format=${format}`
: '/api/v1/_config/schema';
const response = await this.client.get(url);
return response.data;
}
/**
* Get current log level
*/
async getLogLevel(): Promise<LogLevelResponse> {
const response = await this.client.get<LogLevelResponse>('/api/v1/_config/log-level');
return response.data;
}
/**
* Set log level at runtime
*/
async setLogLevel(level: 'debug' | 'info' | 'warning' | 'error'): Promise<LogLevelResponse> {
const response = await this.client.put<LogLevelResponse>(
'/api/v1/_config/log-level',
{ level }
);
return response.data;
}
/**
* Validate endpoint configuration
*/
async validateEndpoint(pathOrName: string, yamlContent: string): Promise<any> {
const slug = pathToSlug(pathOrName);
const response = await this.client.post(
`/api/v1/_config/endpoints/${slug}/validate`,
yamlContent,
{ headers: { 'Content-Type': 'text/plain' } }
);
return response.data;
}
/**
* Reload endpoint configuration from disk
*/
async reloadEndpoint(pathOrName: string): Promise<any> {
const slug = pathToSlug(pathOrName);
const response = await this.client.post(`/api/v1/_config/endpoints/${slug}/reload`);
return response.data;
}
/**
* List all endpoints
*/
async listEndpoints(): Promise<any> {
const response = await this.client.get('/api/v1/_config/endpoints');
return response.data;
}
/**
* Validate raw endpoint YAML for an already-encoded endpoint slug.
* A 400 (invalid config) is returned as a normalized result rather than thrown.
*/
async validateEndpointConfig(slug: string, yamlContent: string): Promise<ValidationResult> {
const response = await this.client.post(
`/api/v1/_config/endpoints/${encodeURIComponent(slug)}/validate`,
yamlContent,
{
headers: { 'Content-Type': 'application/x-yaml' },
validateStatus: (status) => status < 500,
},
);
const result = response.data ?? {};
return {
valid: result.valid ?? false,
errors: result.errors ?? [],
warnings: result.warnings ?? [],
};
}
/**
* Reload an endpoint configuration from disk by already-encoded slug.
*/
async reloadEndpointConfig(slug: string): Promise<ReloadResult> {
const response = await this.client.post(
`/api/v1/_config/endpoints/${encodeURIComponent(slug)}/reload`,
);
const result = response.data ?? {};
return {
success: result.success ?? false,
message: result.message ?? '',
};
}
}
/**
* Create a pre-configured Flapi API client
*/
export function createFlapiClient(options: FlapiApiClientOptions): FlapiApiClient {
return new FlapiApiClient(options);
}
// Export types for convenience
export type { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig };