This repository has been archived by the owner on Mar 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
github.js
84 lines (72 loc) · 2.02 KB
/
github.js
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
import { DISCUSSION_QUERY } from '../graphql/queries';
import { getGraphqlClient } from '../graphql/client';
export const getUserByPat = async token => {
const response = await fetch(
`https://api.github.com/user`,
getRequestHeaders('GET', token)
)
const data = await response.json()
if (response.status !== 200) {
if (data.message === 'Bad credentials') {
throw new Error('The provided PAT is not valid or expired.')
}
throw new Error(data.message)
}
return {
...data,
// TODO: this header is not available, check why ...
exp: response.headers.get('github-authentication-token-expiration')
}
}
const getEntityFromGraphql = async (entityInfo) => {
const { number, owner, repo } = entityInfo
try {
const result = await getGraphqlClient()
.query(DISCUSSION_QUERY, {
number: parseInt(number),
owner: owner,
name: repo
})
.toPromise()
if (result.error) {
return {
error: 'Error while fetching the discussion. Fine-grained PATs are not supported yet.'
}
}
return {
updated_at: result?.data?.repository.discussion.updatedAt
}
} catch (error) {
return {
error
}
}
}
const getEntityFromAPI = async (entityInfo, token) => {
const { owner, repo, type, number } = entityInfo
const effectiveType = type === 'pull' ? 'pulls' : type
const response = await fetch(
`https://api.github.com/repos/${owner}/${repo}/${effectiveType}/${number}`,
getRequestHeaders('GET', token)
)
const data = await response.json()
return data
}
export const getEntity = async (entityInfo, token) => {
const { type } = entityInfo
if (type === 'discussions') {
return await getEntityFromGraphql(entityInfo)
} else {
return await getEntityFromAPI(entityInfo, token)
}
}
const getRequestHeaders = (httpMethod, token) => {
return {
method: httpMethod,
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
}
}
}