-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathvariables.controller.ts
More file actions
398 lines (339 loc) · 11.4 KB
/
variables.controller.ts
File metadata and controls
398 lines (339 loc) · 11.4 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
import {
Controller,
Get,
Post,
Param,
Body,
Query,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { getManifest, type CheckVariable } from '@comp/integration-platform';
import { ConnectionRepository } from '../repositories/connection.repository';
import { ProviderRepository } from '../repositories/provider.repository';
import { CredentialVaultService } from '../services/credential-vault.service';
import { AutoCheckRunnerService } from '../services/auto-check-runner.service';
interface SaveVariablesDto {
variables: Record<string, string | number | boolean | string[]>;
}
interface VariableOption {
value: string;
label: string;
}
interface VariableDefinition {
id: string;
label: string;
type: string;
required: boolean;
default?: string | number | boolean | string[];
helpText?: string;
placeholder?: string;
options?: VariableOption[];
hasDynamicOptions: boolean;
}
@Controller({ path: 'integrations/variables', version: '1' })
export class VariablesController {
private readonly logger = new Logger(VariablesController.name);
constructor(
private readonly connectionRepository: ConnectionRepository,
private readonly providerRepository: ProviderRepository,
private readonly credentialVaultService: CredentialVaultService,
private readonly autoCheckRunnerService: AutoCheckRunnerService,
) {}
/**
* Get all variables required for a provider's checks
*/
@Get('providers/:providerSlug')
async getProviderVariables(
@Param('providerSlug') providerSlug: string,
): Promise<{ variables: VariableDefinition[] }> {
const manifest = getManifest(providerSlug);
if (!manifest) {
throw new HttpException(
`Provider ${providerSlug} not found`,
HttpStatus.NOT_FOUND,
);
}
// Collect all unique variables from manifest-level and checks
const variableMap = new Map<string, CheckVariable>();
// First, add manifest-level variables
for (const variable of manifest.variables || []) {
variableMap.set(variable.id, variable);
}
// Then, add check-specific variables (won't override manifest-level)
for (const check of manifest.checks || []) {
for (const variable of check.variables || []) {
if (!variableMap.has(variable.id)) {
variableMap.set(variable.id, variable);
}
}
}
const variables: VariableDefinition[] = Array.from(
variableMap.values(),
).map((v) => ({
id: v.id,
label: v.label,
type: v.type,
required: v.required || false,
default: v.default,
helpText: v.helpText,
placeholder: v.placeholder,
options: v.options,
hasDynamicOptions: !!v.fetchOptions,
}));
return { variables };
}
/**
* Get variables for a specific connection (with current values)
*/
@Get('connections/:connectionId')
async getConnectionVariables(@Param('connectionId') connectionId: string) {
const connection = await this.connectionRepository.findById(connectionId);
if (!connection) {
throw new HttpException('Connection not found', HttpStatus.NOT_FOUND);
}
const provider = await this.providerRepository.findById(
connection.providerId,
);
if (!provider) {
throw new HttpException('Provider not found', HttpStatus.NOT_FOUND);
}
const manifest = getManifest(provider.slug);
if (!manifest) {
throw new HttpException(
`Manifest for ${provider.slug} not found`,
HttpStatus.NOT_FOUND,
);
}
// Collect all unique variables from manifest-level and checks
const variableMap = new Map<string, CheckVariable>();
// First, add manifest-level variables
for (const variable of manifest.variables || []) {
variableMap.set(variable.id, variable);
}
// Then, add check-specific variables
for (const check of manifest.checks || []) {
for (const variable of check.variables || []) {
if (!variableMap.has(variable.id)) {
variableMap.set(variable.id, variable);
}
}
}
// Get current values from connection
const currentValues =
(connection.variables as Record<string, unknown>) || {};
const variables = Array.from(variableMap.values()).map((v) => ({
id: v.id,
label: v.label,
type: v.type,
required: v.required || false,
default: v.default,
helpText: v.helpText,
placeholder: v.placeholder,
options: v.options,
hasDynamicOptions: !!v.fetchOptions,
currentValue: currentValues[v.id],
}));
return {
connectionId,
providerSlug: provider.slug,
variables,
};
}
/**
* Fetch dynamic options for a variable (requires active connection)
*/
@Get('connections/:connectionId/options/:variableId')
async fetchVariableOptions(
@Param('connectionId') connectionId: string,
@Param('variableId') variableId: string,
): Promise<{ options: VariableOption[] }> {
const connection = await this.connectionRepository.findById(connectionId);
if (!connection) {
throw new HttpException('Connection not found', HttpStatus.NOT_FOUND);
}
if (connection.status !== 'active') {
throw new HttpException(
'Connection must be active to fetch options',
HttpStatus.BAD_REQUEST,
);
}
const provider = await this.providerRepository.findById(
connection.providerId,
);
if (!provider) {
throw new HttpException('Provider not found', HttpStatus.NOT_FOUND);
}
const manifest = getManifest(provider.slug);
if (!manifest) {
throw new HttpException(
`Manifest for ${provider.slug} not found`,
HttpStatus.NOT_FOUND,
);
}
// Find the variable definition (check manifest-level first, then checks)
let variable: CheckVariable | undefined;
// Check manifest-level variables
variable = manifest.variables?.find((v) => v.id === variableId);
// If not found, check in check-specific variables
if (!variable) {
for (const check of manifest.checks || []) {
variable = check.variables?.find((v) => v.id === variableId);
if (variable) break;
}
}
if (!variable) {
throw new HttpException(
`Variable ${variableId} not found`,
HttpStatus.NOT_FOUND,
);
}
if (!variable.fetchOptions) {
// Return static options if available
return { options: variable.options || [] };
}
// Get credentials to make authenticated requests
const credentials =
await this.credentialVaultService.getDecryptedCredentials(connectionId);
if (!credentials?.access_token) {
throw new HttpException(
'No valid credentials found',
HttpStatus.BAD_REQUEST,
);
}
const baseUrl = manifest.baseUrl || '';
const defaultHeaders = manifest.defaultHeaders || {};
const buildHeaders = () => ({
...defaultHeaders,
Authorization: `Bearer ${credentials.access_token}`,
});
// Create minimal context for fetching options
const fetchContext = {
accessToken: credentials.access_token,
fetch: async <T = unknown>(path: string): Promise<T> => {
const url = new URL(path, baseUrl);
const response = await fetch(url.toString(), {
headers: buildHeaders(),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
return data as T;
},
fetchAllPages: async <T = unknown>(path: string): Promise<T[]> => {
const allItems: T[] = [];
let page = 1;
const perPage = 100;
while (page <= 10) {
const url = new URL(path, baseUrl);
url.searchParams.set('page', String(page));
url.searchParams.set('per_page', String(perPage));
const response = await fetch(url.toString(), {
headers: buildHeaders(),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
// Handle both direct array responses and wrapped responses
// e.g., some APIs return { items: [...] } instead of [...]
let items: T[];
if (Array.isArray(data)) {
items = data;
} else if (data && typeof data === 'object') {
// Find the first array property in the response
const arrayValue = Object.values(data).find((v) =>
Array.isArray(v),
) as T[] | undefined;
items = arrayValue ?? [];
} else {
items = [];
}
if (items.length === 0) break;
allItems.push(...items);
if (items.length < perPage) break;
page++;
}
return allItems;
},
graphql: async <T = unknown>(
query: string,
variables?: Record<string, unknown>,
): Promise<T> => {
const endpoint = `${baseUrl}/graphql`;
const response = await fetch(endpoint, {
method: 'POST',
headers: { ...buildHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const result = (await response.json()) as {
data?: T;
errors?: Array<{ message: string }>;
};
if (result.errors?.length) {
throw new Error(
`GraphQL: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data) throw new Error('GraphQL response missing data');
return result.data;
},
};
try {
this.logger.log(`Fetching options for variable ${variableId}`);
const options = await variable.fetchOptions(fetchContext);
return { options };
} catch (error) {
this.logger.error(`Failed to fetch options: ${error}`);
throw new HttpException(
`Failed to fetch options: ${error instanceof Error ? error.message : String(error)}`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Save variable values for a connection
*/
@Post('connections/:connectionId')
async saveConnectionVariables(
@Param('connectionId') connectionId: string,
@Body() body: SaveVariablesDto,
) {
const connection = await this.connectionRepository.findById(connectionId);
if (!connection) {
throw new HttpException('Connection not found', HttpStatus.NOT_FOUND);
}
// Merge with existing variables
const existingVariables =
(connection.variables as Record<string, unknown>) || {};
const newVariables = {
...existingVariables,
...body.variables,
};
await this.connectionRepository.update(connectionId, {
variables: newVariables,
});
this.logger.log(`Saved variables for connection ${connectionId}`);
// Auto-run checks if possible (fire and forget)
this.autoCheckRunnerService
.tryAutoRunChecks(connectionId)
.then((didRun) => {
if (didRun) {
this.logger.log(
`Auto-ran checks for connection ${connectionId} after variables saved`,
);
}
})
.catch((err) => {
this.logger.warn(
`Failed to auto-run checks after saving variables: ${err.message}`,
);
});
return { success: true, variables: newVariables };
}
}