This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
GitlabClient.ts
181 lines (152 loc) · 4.37 KB
/
GitlabClient.ts
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
import fetch, { RequestInit, Response } from 'node-fetch';
import {
GitLabUser,
GitLabGroup,
GitLabProject,
GitLabMergeRequest,
GitLabUserRef,
GitLabMergeRequestApproval,
} from './types';
import { IntegrationError } from '@jupiterone/integration-sdk/src/errors';
export enum HttpMethod {
GET = 'get',
POST = 'post',
}
export class GitlabClient {
private readonly baseUrl: string;
private readonly personalToken: string;
private readonly lastRun: Date;
constructor(baseUrl: string, personalToken: string, lastRun: Date) {
this.baseUrl = baseUrl;
this.personalToken = personalToken;
this.lastRun = lastRun;
}
async fetchAccount(): Promise<GitLabUser> {
return this.makeSingularRequest(HttpMethod.GET, '/user');
}
async fetchUser(id: number): Promise<GitLabUser> {
return this.makeSingularRequest(HttpMethod.GET, `/users/${id}`);
}
async fetchGroups(): Promise<GitLabGroup[]> {
return this.makePaginatedRequest(HttpMethod.GET, '/groups');
}
async fetchProjects(): Promise<GitLabProject[]> {
return this.makePaginatedRequest(HttpMethod.GET, '/projects', null, {
owned: true,
});
}
async fetchUsers(): Promise<GitLabUser[]> {
return this.makePaginatedRequest(HttpMethod.GET, '/users');
}
async fetchProjectMergeRequests(
projectId: number,
): Promise<GitLabMergeRequest[]> {
return this.makePaginatedRequest(
HttpMethod.GET,
`/projects/${projectId}/merge_requests`,
1,
{
updated_after: this.lastRun.toISOString(),
},
);
}
async fetchMergeRequestApprovals(
projectId: number,
mergeRequestId: number,
): Promise<GitLabMergeRequestApproval> {
try {
const result: GitLabMergeRequestApproval = await this.makeSingularRequest(
HttpMethod.GET,
`/projects/${projectId}/merge_requests/${mergeRequestId}/approvals`,
);
return result;
} catch (err) {
console.error(err);
return {} as GitLabMergeRequestApproval;
}
}
async fetchProjectMembers(projectId: number): Promise<GitLabUserRef[]> {
return this.makePaginatedRequest(
HttpMethod.GET,
`/projects/${projectId}/members/all`,
);
}
async fetchGroupMembers(groupId: number): Promise<GitLabUserRef[]> {
return this.makePaginatedRequest(
HttpMethod.GET,
`/groups/${groupId}/members/all`,
);
}
async fetchGroupProjects(groupId: number): Promise<GitLabProject[]> {
return this.makePaginatedRequest(
HttpMethod.GET,
`/groups/${groupId}/projects`,
);
}
async fetchGroupSubgroups(groupId: number): Promise<GitLabGroup[]> {
return this.makePaginatedRequest(
HttpMethod.GET,
`/groups/${groupId}/subgroups`,
);
}
private async makeRequest(
method: HttpMethod,
url: string,
): Promise<Response> {
const options: RequestInit = {
method,
headers: {
'Private-Token': this.personalToken,
},
};
const response: Response = await fetch(
`${this.baseUrl}/api/v4${url}`,
options,
);
if (!response) {
throw new Error(`No response from '${this.baseUrl}/api/v4${url}'`);
}
if (!response.ok) {
throw new IntegrationError({
code: response.status.toString(),
message: `Request '${this.baseUrl}/api/v4${url}' failed: ${response.statusText}`,
});
}
return response;
}
private async makeSingularRequest<T>(
method: HttpMethod,
url: string,
): Promise<T | null> {
const response = await this.makeRequest(method, `${url}`);
return response.json();
}
private async makePaginatedRequest<T>(
method: HttpMethod,
url: string,
maxPages?: number,
params?: {},
): Promise<T[]> {
const results: T[] = [];
let page = 0;
let totalPages = 1;
const pageLimit = maxPages || Number.POSITIVE_INFINITY;
do {
const queryParams = Object.entries(params || {})
.map(([k, v]) => `${k}=${v}`)
.join('&');
const response = await this.makeRequest(
method,
`${url}?page=${++page}&per_page=100${
queryParams ? '&' + queryParams : ''
}`,
);
totalPages = parseInt(response.headers.get('X-Total-Pages'), 10);
const result = await response.json();
if (result) {
results.push(result);
}
} while (page < totalPages && page < pageLimit);
return [].concat(...results);
}
}