/
Slack.ts
109 lines (96 loc) · 3.34 KB
/
Slack.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
import { ICommonObject, INode, INodeData, INodeExecutionData, INodeParams, NodeType } from '../../src/Interface'
import { handleErrorMessage, returnNodeExecutionData } from '../../src/utils'
import axios, { AxiosRequestConfig, Method } from 'axios'
interface ISlackWebhook {
text?: string
blocks?: any[]
}
class Slack implements INode {
label: string
name: string
type: NodeType
description: string
version: number
icon: string
category: string
incoming: number
outgoing: number
inputParameters?: INodeParams[]
constructor() {
this.label = 'Slack'
this.name = 'slack'
this.icon = 'slack.svg'
this.type = 'action'
this.category = 'Communication'
this.version = 1.0
this.description = 'Post message in Slack channel'
this.incoming = 1
this.outgoing = 1
this.inputParameters = [
{
label: 'Webhook URL',
name: 'webhookUrl',
type: 'string',
default: '',
description: 'Webhook URL for the channel. Learn more: https://api.slack.com/messaging/webhooks'
},
{
label: 'Message',
description: 'Message contents',
name: 'text',
type: 'string',
default: ''
}
] as INodeParams[]
}
async run(nodeData: INodeData): Promise<INodeExecutionData[] | null> {
const inputParametersData = nodeData.inputParameters
if (inputParametersData === undefined) {
throw new Error('Required data missing')
}
const returnData: ICommonObject[] = []
const body: ISlackWebhook = {}
const webhookUrl = inputParametersData.webhookUrl as string
const text = inputParametersData.text as string
body.text = text
let responseData: any
let maxRetries = 5
do {
try {
const axiosConfig: AxiosRequestConfig = {
method: 'POST' as Method,
url: `${webhookUrl}`,
data: body,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}
const response = await axios(axiosConfig)
responseData = response.data
break
} catch (error) {
// Rate limit exceeded
if (error.response && error.response.status === 429) {
const retryAfter = error.response?.headers['retry-after'] || 60
await new Promise<void>((resolve, _) => {
setTimeout(() => {
resolve()
}, retryAfter * 1000)
})
continue
}
throw handleErrorMessage(error)
}
} while (--maxRetries)
if (maxRetries <= 0) {
throw new Error('Error posting message to Slack channel. Max retries limit was reached.')
}
if (Array.isArray(responseData)) {
returnData.push(...responseData)
} else {
returnData.push(responseData)
}
return returnNodeExecutionData(returnData)
}
}
module.exports = { nodeClass: Slack }