-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
index.ts
504 lines (472 loc) · 13.1 KB
/
index.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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
import { VssueAPI } from 'vssue'
import axios, {
AxiosInstance,
AxiosRequestConfig,
} from 'axios'
import {
buildQuery,
buildURL,
concatURL,
getCleanURL,
parseQuery,
} from '@vssue/utils'
import {
normalizeUser,
normalizeIssue,
normalizeComment,
normalizeReactions,
mapReactionName,
} from './utils'
/**
* GitLab API V4
*
* @see https://docs.gitlab.com/ce/api/
* @see https://docs.gitlab.com/ce/api/oauth2.html
*/
export default class GitlabV4 implements VssueAPI.Instance {
baseURL: string
owner: string
repo: string
labels: Array<string>
clientId: string
state: string
$http: AxiosInstance
private _encodedRepo: string
constructor ({
baseURL = 'https://gitlab.com',
owner,
repo,
labels,
clientId,
state,
}: VssueAPI.Options) {
this.baseURL = baseURL
this.owner = owner
this.repo = repo
this.labels = labels
this.clientId = clientId
this.state = state
// @see https://docs.gitlab.com/ce/api/README.html#namespaced-path-encoding
this._encodedRepo = encodeURIComponent(`${this.owner}/${this.repo}`)
this.$http = axios.create({
baseURL: concatURL(baseURL, 'api/v4'),
headers: {
'Accept': 'application/json',
},
})
}
/**
* The platform api info
*/
get platform (): VssueAPI.Platform {
return {
name: 'GitLab',
link: this.baseURL,
version: 'v4',
meta: {
reactable: true,
sortable: true,
},
}
}
/**
* Redirect to the authorization page of platform.
*
* @see https://docs.gitlab.com/ce/api/oauth2.html#1-requesting-authorization-code
*/
redirectAuth (): void {
window.location.href = buildURL(concatURL(this.baseURL, 'oauth/authorize'), {
client_id: this.clientId,
redirect_uri: window.location.href,
response_type: 'token',
state: this.state,
})
}
/**
* Handle authorization.
*
* @return A string for access token, `null` for no authorization code
*
* @see https://docs.gitlab.com/ce/api/oauth2.html#implicit-grant-flow
*
* @remarks
* If the `access_token` and `state` exist in the query, and the `state` matches, remove them from query, and return the access token.
*/
async handleAuth (): Promise<VssueAPI.AccessToken> {
const hash = parseQuery(window.location.hash.slice(1))
if (!hash.access_token || hash.state !== this.state) {
return null
}
const accessToken = hash.access_token
delete hash.access_token
delete hash.token_type
delete hash.expires_in
delete hash.state
const hashString = buildQuery(hash)
const newHash = hashString ? `#${hashString}` : ''
const replaceURL = `${getCleanURL(window.location.href)}${window.location.search}${newHash}`
window.history.replaceState(null, '', replaceURL)
return accessToken
}
/**
* Get the logged-in user with access token.
*
* @param options.accessToken - User access token
*
* @return The user
*/
async getUser ({
accessToken,
}: {
accessToken: VssueAPI.AccessToken
}): Promise<VssueAPI.User> {
const { data } = await this.$http.get('user', {
headers: { 'Authorization': `Bearer ${accessToken}` },
})
return normalizeUser(data)
}
/**
* Get issue of this page according to the issue id or the issue title
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.issueTitle - The title of issue
*
* @return The issue
*
* @see https://docs.gitlab.com/ce/api/issues.html#single-issue
* @see https://docs.gitlab.com/ce/api/issues.html#list-issues
* @see https://docs.gitlab.com/ce/api/README.html#pagination
*/
async getIssue ({
accessToken,
issueId,
issueTitle,
}: {
accessToken: VssueAPI.AccessToken
issueId?: string | number
issueTitle?: string
}): Promise<VssueAPI.Issue | null> {
const options: AxiosRequestConfig = {}
if (accessToken) {
options.headers = {
'Authorization': `Bearer ${accessToken}`,
}
}
if (issueId) {
try {
const { data } = await this.$http.get(`projects/${this._encodedRepo}/issues/${issueId}`, options)
return normalizeIssue(data)
} catch (e) {
if (e.response && e.response.status === 404) {
return null
} else {
throw e
}
}
} else {
options.params = {
labels: this.labels.join(','),
order_by: 'created_at',
sort: 'asc',
search: issueTitle,
}
const { data } = await this.$http.get(`projects/${this._encodedRepo}/issues`, options)
const issue = data.map(normalizeIssue).find(item => item.title === issueTitle)
return issue || null
}
}
/**
* Create a new issue
*
* @param options.accessToken - User access token
* @param options.title - The title of issue
* @param options.content - The content of issue
*
* @return The created issue
*
* @see https://docs.gitlab.com/ce/api/issues.html#new-issue
*/
async postIssue ({
accessToken,
title,
content,
}: {
accessToken: VssueAPI.AccessToken
title: string
content: string
}): Promise<VssueAPI.Issue> {
const { data } = await this.$http.post(`projects/${this._encodedRepo}/issues`, {
title,
description: content,
labels: this.labels.join(','),
}, {
headers: { 'Authorization': `Bearer ${accessToken}` },
})
return normalizeIssue(data)
}
/**
* Get comments of this page according to the issue id
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.query - The query parameters
*
* @return The comments
*
* @see https://docs.gitlab.com/ce/api/notes.html#list-project-issue-notes
* @see https://docs.gitlab.com/ce/api/README.html#pagination
*
* @remarks
* Cannot get the HTML content and the reactions (award_emoji) here.
* So have to request them via `markdown` and `award_emoji` API.
*/
async getComments ({
accessToken,
issueId,
query: {
page = 1,
perPage = 10,
sort = 'desc',
} = {},
}: {
accessToken: VssueAPI.AccessToken
issueId: string | number
query?: Partial<VssueAPI.Query>
}): Promise<VssueAPI.Comments> {
const options: AxiosRequestConfig = {
params: {
// pagination
'page': page,
'per_page': perPage,
'order_by': 'created_at',
'sort': sort,
},
}
if (accessToken) {
options.headers = {
'Authorization': `Bearer ${accessToken}`,
}
}
const response = await this.$http.get(`projects/${this._encodedRepo}/issues/${issueId}/notes`, options)
const commentsRaw = response.data
// gitlab api v4 should get parsed markdown content and reactions by other api
// this is potentially to cause 429 Too Many Requests
const getCommentsMeta: Array<Promise<void>> = []
for (const comment of commentsRaw) {
getCommentsMeta.push((async () => {
comment.body_html = await this.getMarkdownContent({
accessToken: accessToken,
contentRaw: comment.body,
})
})())
getCommentsMeta.push((async () => {
comment.reactions = await this.getCommentReactions({
accessToken: accessToken,
issueId: issueId,
commentId: comment.id,
})
})())
}
await Promise.all(getCommentsMeta)
return {
count: Number(response.headers['x-total']),
page: Number(response.headers['x-page']),
perPage: Number(response.headers['x-per-page']),
data: commentsRaw.map(normalizeComment),
}
}
/**
* Create a new comment
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.content - The content of comment
*
* @return The created comment
*
* @see https://docs.gitlab.com/ce/api/notes.html#create-new-issue-note
*/
async postComment ({
accessToken,
issueId,
content,
}: {
accessToken: VssueAPI.AccessToken
issueId: string | number
content: string
}): Promise<VssueAPI.Comment> {
const { data } = await this.$http.post(`projects/${this._encodedRepo}/issues/${issueId}/notes`, {
body: content,
}, {
headers: { 'Authorization': `Bearer ${accessToken}` },
})
return normalizeComment(data)
}
/**
* Edit a comment
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.commentId - The id of comment
* @param options.content - The content of comment
*
* @return The edited comment
*
* @see https://docs.gitlab.com/ce/api/notes.html#modify-existing-issue-note
*/
async putComment ({
accessToken,
issueId,
commentId,
content,
}: {
accessToken: VssueAPI.AccessToken
issueId: string | number
commentId: string | number
content: string
}): Promise<VssueAPI.Comment> {
const { data } = await this.$http.put(`projects/${this._encodedRepo}/issues/${issueId}/notes/${commentId}`, {
body: content,
}, {
headers: { 'Authorization': `Bearer ${accessToken}` },
})
const [contentHTML, reactions] = await Promise.all([
this.getMarkdownContent({
accessToken: accessToken,
contentRaw: data.body,
}),
this.getCommentReactions({
accessToken: accessToken,
issueId: issueId,
commentId: data.id,
}),
])
data.body_html = contentHTML
data.reactions = reactions
return normalizeComment(data)
}
/**
* Delete a comment
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.commentId - The id of comment
*
* @return `true` if succeed, `false` if failed
*
* @see https://docs.gitlab.com/ce/api/notes.html#delete-an-issue-note
*/
async deleteComment ({
accessToken,
issueId,
commentId,
}: {
accessToken: VssueAPI.AccessToken
issueId: string | number
commentId: string | number
}): Promise<boolean> {
const { status } = await this.$http.delete(`projects/${this._encodedRepo}/issues/${issueId}/notes/${commentId}`, {
headers: { 'Authorization': `Bearer ${accessToken}` },
})
return status === 204
}
/**
* Get reactions of a comment
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.commentId - The id of comment
*
* @return The comments
*
* @see https://docs.gitlab.com/ce/api/award_emoji.html#list-an-awardables-award-emoji
*/
async getCommentReactions ({
accessToken,
issueId,
commentId,
}: {
accessToken: VssueAPI.AccessToken
issueId: string | number
commentId: string | number
}): Promise<VssueAPI.Reactions> {
const { data } = await this.$http.get(`projects/${this._encodedRepo}/issues/${issueId}/notes/${commentId}/award_emoji`, {
headers: { 'Authorization': `Bearer ${accessToken}` },
})
return normalizeReactions(data)
}
/**
* Create a new reaction of a comment
*
* @param options.accessToken - User access token
* @param options.issueId - The id of issue
* @param options.commentId - The id of comment
* @param options.reaction - The reaction
*
* @return `true` if succeed, `false` if already token
*
* @see https://docs.gitlab.com/ce/api/award_emoji.html#award-a-new-emoji
*/
async postCommentReaction ({
issueId,
commentId,
reaction,
accessToken,
}: {
accessToken: VssueAPI.AccessToken
issueId: string | number
commentId: string | number
reaction: keyof VssueAPI.Reactions
}): Promise<boolean> {
try {
const response = await this.$http.post(`projects/${this._encodedRepo}/issues/${issueId}/notes/${commentId}/award_emoji`, {
name: mapReactionName(reaction),
}, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
})
return response.status === 201
} catch (e) {
// it could be a bug of gitlab
// if a reaction (award emoji) has already existed, it returns a 404 response with a buggy message
// have submitted an issue: https://gitlab.com/gitlab-org/gitlab-ce/issues/56147
/* istanbul ignore next */
if (e.response && e.response.status === 404) {
return false
} else {
throw e
}
}
}
/**
* Get the parse HTML of markdown content
*
* @param options.accessToken - User access token
* @param options.contentRaw - The id of issue
*
* @return The HTML string of parsed markdown
*
* @see https://docs.gitlab.com/ce/api/markdown.html
*/
async getMarkdownContent ({
accessToken,
contentRaw,
}: {
accessToken?: string | null,
contentRaw: string,
}): Promise<string> {
const options: AxiosRequestConfig = {}
if (accessToken) {
options.headers = {
'Authorization': `Bearer ${accessToken}`,
}
}
const { data } = await this.$http.post(`markdown`, {
text: contentRaw,
gfm: true,
}, options)
return data.html
}
}