-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapi-helper.ts
More file actions
453 lines (414 loc) · 13.1 KB
/
api-helper.ts
File metadata and controls
453 lines (414 loc) · 13.1 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import type { APIResponse } from "@playwright/test";
import { request, expect } from "@playwright/test";
import type { GroupEntity, UserEntity } from "@backstage/catalog-model";
import { GITHUB_API_ENDPOINTS } from "./api-endpoints.js";
export class APIHelper {
private static githubAPIVersion = "2022-11-28";
private staticToken: string = "";
private baseUrl: string = "";
useStaticToken = false;
static async githubRequest(
method: string,
url: string,
body?: string | object,
): Promise<APIResponse> {
const context = await request.newContext();
const options: {
method: string;
headers: Record<string, string>;
data?: string | object;
} = {
method: method,
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${process.env.VAULT_GITHUB_USER_TOKEN}`,
"X-GitHub-Api-Version": this.githubAPIVersion,
},
};
if (body) {
options.data = body;
}
const response = await context.fetch(url, options);
return response;
}
static async getGithubPaginatedRequest(
url: string,
pageNo: number = 1,
response: unknown[] = [],
): Promise<unknown[]> {
const fullUrl = `${url}&page=${pageNo}`;
const result = await this.githubRequest("GET", fullUrl);
const body = await result.json();
if (!Array.isArray(body)) {
throw new Error(
`Expected array but got ${typeof body}: ${JSON.stringify(body)}`,
);
}
if (body.length === 0) {
return response;
}
response = [...response, ...body];
return await this.getGithubPaginatedRequest(url, pageNo + 1, response);
}
static async createGitHubRepo(owner: string, repoName: string) {
const response = await APIHelper.githubRequest(
"POST",
GITHUB_API_ENDPOINTS.createRepo(owner),
{
name: repoName,
private: false,
},
);
expect(response.status() === 201 || response.ok()).toBeTruthy();
}
static async createGitHubRepoWithFile(
owner: string,
repoName: string,
filename: string,
fileContent: string,
) {
// Create the repository
await APIHelper.createGitHubRepo(owner, repoName);
await new Promise((resolve) => setTimeout(resolve, 2000));
// Add the specified file
await APIHelper.createFileInRepo(
owner,
repoName,
filename,
fileContent,
`Add ${filename} file`,
);
}
static async createFileInRepo(
owner: string,
repoName: string,
filePath: string,
content: string,
commitMessage: string,
branch = "main",
) {
const encodedContent = Buffer.from(content).toString("base64");
const response = await APIHelper.githubRequest(
"PUT",
`${GITHUB_API_ENDPOINTS.contents(owner, repoName)}/${filePath}`,
{
message: commitMessage,
content: encodedContent,
branch: branch,
},
);
expect(response.status() === 201 || response.ok()).toBeTruthy();
}
static async initCommit(owner: string, repo: string, branch = "main") {
const content = Buffer.from(
"This is the initial commit for the repository.",
).toString("base64");
const response = await APIHelper.githubRequest(
"PUT",
`${GITHUB_API_ENDPOINTS.contents(owner, repo)}/initial-commit.md`,
{
message: "Initial commit",
content: content,
branch: branch,
},
);
expect(response.status() === 201 || response.ok()).toBeTruthy();
}
static async deleteGitHubRepo(owner: string, repoName: string) {
await APIHelper.githubRequest(
"DELETE",
GITHUB_API_ENDPOINTS.deleteRepo(owner, repoName),
);
}
static async mergeGitHubPR(
owner: string,
repoName: string,
pullNumber: number,
) {
await APIHelper.githubRequest(
"PUT",
GITHUB_API_ENDPOINTS.mergePR(owner, repoName, pullNumber),
);
}
static async getGitHubPRs(
owner: string,
repoName: string,
state: "open" | "closed" | "all",
paginated = false,
) {
const url = GITHUB_API_ENDPOINTS.pull(owner, repoName, state);
if (paginated) {
return await APIHelper.getGithubPaginatedRequest(url);
}
const response = await APIHelper.githubRequest("GET", url);
return response.json();
}
static async getfileContentFromPR(
owner: string,
repoName: string,
pr: number,
filename: string,
): Promise<string> {
const response = await APIHelper.githubRequest(
"GET",
GITHUB_API_ENDPOINTS.pullFiles(owner, repoName, pr),
);
const fileRawUrl = (await response.json()).find(
(file: { filename: string }) => file.filename === filename,
).raw_url;
const rawFileContent = await (
await APIHelper.githubRequest("GET", fileRawUrl)
).text();
return rawFileContent;
}
async getGuestToken(): Promise<string> {
const context = await request.newContext();
const response = await context.post("/api/auth/guest/refresh");
expect(response.status()).toBe(200);
const data = await response.json();
return data.backstageIdentity.token;
}
async getGuestAuthHeader(): Promise<{ [key: string]: string }> {
const token = await this.getGuestToken();
const headers = {
Authorization: `Bearer ${token}`,
};
return headers;
}
async setStaticToken(token: string) {
this.useStaticToken = true;
this.staticToken = "Bearer " + token;
}
async setBaseUrl(url: string) {
this.baseUrl = url;
}
static async apiRequestWithStaticToken(
method: string,
url: string,
staticToken: string,
body?: string | object,
): Promise<APIResponse> {
const context = await request.newContext();
const options = {
method: method,
headers: {
Accept: "application/json",
Authorization: `${staticToken}`,
},
...(body && { data: body }),
};
const response = await context.fetch(url, options);
return response;
}
async getAllCatalogUsersFromAPI() {
const url = `${this.baseUrl}/api/catalog/entities/by-query?orderField=metadata.name%2Casc&filter=kind%3Duser`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"GET",
url,
token,
);
return response.json();
}
async getAllCatalogLocationsFromAPI() {
const url = `${this.baseUrl}/api/catalog/entities/by-query?orderField=metadata.name%2Casc&filter=kind%3Dlocation`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"GET",
url,
token,
);
return response.json();
}
async getAllCatalogGroupsFromAPI() {
const url = `${this.baseUrl}/api/catalog/entities/by-query?orderField=metadata.name%2Casc&filter=kind%3Dgroup`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"GET",
url,
token,
);
return response.json();
}
async getGroupEntityFromAPI(group: string) {
const url = `${this.baseUrl}/api/catalog/entities/by-name/group/default/${group}`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"GET",
url,
token,
);
return response.json();
}
async getCatalogUserFromAPI(user: string) {
const url = `${this.baseUrl}/api/catalog/entities/by-name/user/default/${user}`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"GET",
url,
token,
);
return response.json();
}
async deleteUserEntityFromAPI(user: string) {
const r: UserEntity = await this.getCatalogUserFromAPI(user);
if (!r.metadata || !r.metadata.uid) {
return;
}
const url = `${this.baseUrl}/api/catalog/entities/by-uid/${r.metadata.uid}`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"DELETE",
url,
token,
);
return response.statusText;
}
async getCatalogGroupFromAPI(group: string) {
const url = `${this.baseUrl}/api/catalog/entities/by-name/group/default/${group}`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"GET",
url,
token,
);
return response.json();
}
async deleteGroupEntityFromAPI(group: string) {
const r: GroupEntity = await this.getCatalogGroupFromAPI(group);
const url = `${this.baseUrl}/api/catalog/entities/by-uid/${r.metadata.uid}`;
const token = this.useStaticToken ? this.staticToken : "";
const response = await APIHelper.apiRequestWithStaticToken(
"DELETE",
url,
token,
);
return response.statusText;
}
async scheduleEntityRefreshFromAPI(
entity: string,
kind: string,
token: string,
) {
const url = `${this.baseUrl}/api/catalog/refresh`;
const reqBody = { entityRef: `${kind}:default/${entity}` };
const responseRefresh = await APIHelper.apiRequestWithStaticToken(
"POST",
url,
token,
reqBody,
);
return responseRefresh.status();
}
/**
* Fetches the UID of an entity by its name from the Backstage catalog.
*
* @param name - The name of the entity (e.g., 'hello-world-2').
* @returns The UID string if found, otherwise undefined.
*/
static async getEntityUidByName(name: string): Promise<string | undefined> {
const baseUrl = process.env.RHDH_BASE_URL;
const url = `${baseUrl}/api/catalog/entities/by-name/template/default/${name}`;
const context = await request.newContext();
const response = await context.get(url);
if (response.status() !== 200) {
return undefined;
}
const data = await response.json();
return data?.metadata?.uid;
}
/**
* Deletes a location from the Backstage catalog by its UID.
*
* @param uid - The UID of the location to delete.
* @returns The status code of the delete operation.
*/
static async deleteLocationByUid(uid: string): Promise<number> {
const baseUrl = process.env.RHDH_BASE_URL;
const url = `${baseUrl}/api/catalog/locations/${uid}`;
const context = await request.newContext();
const response = await context.delete(url);
return response.status();
}
/**
* Fetches the UID of a Template entity by its name and namespace from the Backstage catalog.
*
* @param name - The name of the template entity (e.g., 'hello-world-2').
* @param namespace - The namespace of the template entity (default: 'default').
* @returns The UID string if found, otherwise undefined.
*/
static async getTemplateEntityUidByName(
name: string,
namespace: string = "default",
): Promise<string | undefined> {
const baseUrl = process.env.RHDH_BASE_URL;
const url = `${baseUrl}/api/catalog/locations/by-entity/template/${namespace}/${name}`;
const context = await request.newContext();
const response = await context.get(url);
if (response.status() === 200) {
const data = await response.json();
return data?.metadata?.uid;
}
if (response.status() === 404) {
return undefined;
}
return undefined;
}
/**
* Deletes an entity location from the Backstage catalog by its ID.
*
* @param id - The ID of the entity to delete.
* @returns The status code of the delete operation.
*/
static async deleteEntityLocationById(id: string): Promise<number> {
const baseUrl = process.env.RHDH_BASE_URL;
const url = `${baseUrl}/api/catalog/locations/${id}`;
const context = await request.newContext();
const response = await context.delete(url);
return response.status();
}
/**
* Registers a new location in the Backstage catalog.
*
* @param target - The target URL of the location to register.
* @returns The status code of the registration operation.
*/
static async registerLocation(target: string): Promise<number> {
const baseUrl = process.env.RHDH_BASE_URL;
const url = `${baseUrl}/api/catalog/locations`;
const context = await request.newContext();
const response = await context.post(url, {
data: {
type: "url",
target,
},
headers: {
"Content-Type": "application/json",
},
});
return response.status();
}
/**
* Fetches the ID of a location from the Backstage catalog by its target URL.
*
* @param target - The target URL of the location to search for.
* @returns The ID string if found, otherwise undefined.
*/
static async getLocationIdByTarget(
target: string,
): Promise<string | undefined> {
const baseUrl = process.env.RHDH_BASE_URL;
const url = `${baseUrl}/api/catalog/locations`;
const context = await request.newContext();
const response = await context.get(url);
if (response.status() !== 200) {
return undefined;
}
const data = await response.json();
// data is expected to be an array of objects with a 'data' property
const location = (Array.isArray(data) ? data : []).find(
(entry) => entry?.data?.target === target,
);
return location?.data?.id;
}
}