|
1 | 1 | 'use strict'
|
2 | 2 |
|
3 | 3 | const githubClient = require('./github-client')
|
| 4 | +const GQL = require('./github-graphql-client') |
| 5 | + |
| 6 | +const getPRComments = `query getPRComments($owner: String!, $repo: String!, $number: Int!, $cursor: String){ |
| 7 | + repository(owner: $owner, name: $repo) { |
| 8 | + pullRequest(number: $number) { |
| 9 | + comments(first: 20, after:$cursor) { |
| 10 | + nodes { |
| 11 | + id |
| 12 | + body |
| 13 | + viewerDidAuthor |
| 14 | + } |
| 15 | + pageInfo { |
| 16 | + endCursor |
| 17 | + hasNextPage |
| 18 | + } |
| 19 | + } |
| 20 | + labels(first: 15) { |
| 21 | + nodes { |
| 22 | + name |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | +}` |
| 28 | + |
| 29 | +function graphQlIdToRestId (nodeId) { |
| 30 | + const decoded = Buffer.from(nodeId, 'base64').toString() |
| 31 | + return decoded.match(/\d+$/)[0] |
| 32 | +} |
| 33 | + |
| 34 | +exports.getFirstBotComment = function getFirstBotComment ({ owner, repo, number }, cursor = null) { |
| 35 | + return GQL(getPRComments, { owner, repo, number, cursor }).then(data => { |
| 36 | + const { nodes, pageInfo } = data.repository.pullRequest.comments |
| 37 | + const firstBotComment = nodes.find(e => e.viewerDidAuthor) |
| 38 | + if (firstBotComment) { |
| 39 | + return firstBotComment |
| 40 | + } |
| 41 | + if (pageInfo.hasNextPage) { |
| 42 | + return exports.getFirstBotComment({ owner, repo, number }, pageInfo.endCursor) |
| 43 | + } |
| 44 | + return null |
| 45 | + }) |
| 46 | +} |
4 | 47 |
|
5 | 48 | exports.createPrComment = function createPrComment ({ owner, repo, number, logger }, body) {
|
6 |
| - githubClient.issues.createComment({ |
7 |
| - owner, |
8 |
| - repo, |
9 |
| - number, |
10 |
| - body |
11 |
| - }, (err) => { |
12 |
| - if (err) { |
13 |
| - logger.error(err, 'Error while creating comment on GitHub') |
| 49 | + exports.getFirstBotComment({ owner, repo, number, logger }).then((comment) => { |
| 50 | + if (comment) { |
| 51 | + const { id: nodeId, body: oldBody } = comment |
| 52 | + const newBody = `${oldBody}\n${body}` |
| 53 | + const id = graphQlIdToRestId(nodeId) |
| 54 | + return githubClient.issues.editComment({ owner, repo, id, body: newBody }) |
14 | 55 | }
|
| 56 | + return githubClient.issues.createComment({ owner, repo, number, body }) |
| 57 | + }).catch((err) => { |
| 58 | + logger.error(err, 'Error while creating comment on GitHub') |
| 59 | + // swallow error |
15 | 60 | })
|
16 | 61 | }
|
0 commit comments