forked from nodejs/github-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-comment.js
More file actions
61 lines (56 loc) · 1.81 KB
/
github-comment.js
File metadata and controls
61 lines (56 loc) · 1.81 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
'use strict'
const githubClient = require('./github-client')
const GQL = require('./github-graphql-client')
const getPRComments = `query getPRComments($owner: String!, $repo: String!, $number: Int!, $cursor: String){
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
comments(first: 20, after:$cursor) {
nodes {
id
body
viewerDidAuthor
}
pageInfo {
endCursor
hasNextPage
}
}
labels(first: 15) {
nodes {
name
}
}
}
}
}`
function graphQlIdToRestId (nodeId) {
const decoded = Buffer.from(nodeId, 'base64').toString()
return decoded.match(/\d+$/)[0]
}
exports.getFirstBotComment = function getFirstBotComment ({ owner, repo, number }, cursor = null) {
return GQL(getPRComments, { owner, repo, number, cursor }).then(data => {
const { nodes, pageInfo } = data.repository.pullRequest.comments
const firstBotComment = nodes.find(e => e.viewerDidAuthor)
if (firstBotComment) {
return firstBotComment
}
if (pageInfo.hasNextPage) {
return exports.getFirstBotComment({ owner, repo, number }, pageInfo.endCursor)
}
return null
})
}
exports.createPrComment = function createPrComment ({ owner, repo, number, logger }, body) {
exports.getFirstBotComment({ owner, repo, number, logger }).then((comment) => {
if (comment) {
const { id: nodeId, body: oldBody } = comment
const newBody = `${oldBody}\n${body}`
const id = graphQlIdToRestId(nodeId)
return githubClient.issues.editComment({ owner, repo, id, body: newBody })
}
return githubClient.issues.createComment({ owner, repo, number, body })
}).catch((err) => {
logger.error(err, 'Error while creating comment on GitHub')
// swallow error
})
}