Skip to content

Commit

Permalink
fix: slackToken based message returns a JSON object (#89)
Browse files Browse the repository at this point in the history
This correctly handles the return type of the chat.postMessage fetch request. This also means that "success" for the two methods of sending a slack message need to be handled differently
  • Loading branch information
SimeonC authored Jan 24, 2022
1 parent 4a31a5f commit e85e59c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
10 changes: 7 additions & 3 deletions lib/postMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module.exports = async (
) => {
let response
let bodyText
let isSuccess
try {
if (slackIcon) {
const hasSemicolons = slackIcon.startsWith(':') && slackIcon.endsWith(':')
Expand All @@ -23,11 +24,13 @@ module.exports = async (
response = await fetch('https://slack.com/api/chat.postMessage', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Bearer ${slackToken}`
},
body: JSON.stringify(message)
})
bodyText = await response.text()
isSuccess = response.ok && JSON.parse(bodyText).ok
} else {
if (slackChannel) {
message.channel = slackChannel
Expand All @@ -39,13 +42,14 @@ module.exports = async (
},
body: JSON.stringify(message)
})
bodyText = await response.text()
isSuccess = response.ok && bodyText === 'ok'
}
bodyText = await response.text()
} catch (e) {
throw new SemanticReleaseError(e.message, 'SLACK CONNECTION FAILED')
}

if (!response.ok || bodyText !== 'ok') {
if (!isSuccess) {
logger.log('JSON message format invalid: ' + bodyText)
throw new SemanticReleaseError(bodyText, 'INVALID SLACK COMMAND')
}
Expand Down
4 changes: 2 additions & 2 deletions test/postMessage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ describe('test postMessage with token/channel', () => {
it('should pass if response is 200 "ok"', async () => {
nock(slackPostMessageDomain)
.post(slackPostMessagePath)
.reply(200, 'ok')
.reply(200, JSON.stringify({ ok: true }))
assert.ifError(await postToken())
})

it('should fail if response text is not "ok"', async () => {
const response = 'not ok'
const response = JSON.stringify({ ok: false })
nock(slackPostMessageDomain)
.post(slackPostMessagePath)
.reply(200, response)
Expand Down

0 comments on commit e85e59c

Please sign in to comment.