|
| 1 | +const models = require('../../models/index'); |
| 2 | +const { postChat } = require('../../middlewares/index'); |
| 3 | + |
| 4 | +require('dotenv').config(); |
| 5 | + |
| 6 | +const message = { |
| 7 | + message: 'there was an error posting your message to slack, try again', |
| 8 | + status: 'failure', |
| 9 | +}; |
| 10 | + |
| 11 | +module.exports = { |
| 12 | + // eslint-disable-next-line max-lines-per-function |
| 13 | + createAppChat: async (req, res) => { |
| 14 | + if (req.body.text.length === 0) { |
| 15 | + return res |
| 16 | + .status(400) |
| 17 | + .send({ message: 'Text is required', status: 'failure' }); |
| 18 | + } |
| 19 | + let channelID; |
| 20 | + const { incidentId } = req.body; |
| 21 | + try { |
| 22 | + const SlackChannel = await models.SlackChannels.findAll({ |
| 23 | + attributes: ['channelId'], |
| 24 | + where: { incidentId: incidentId }, |
| 25 | + }); |
| 26 | + const { channelId } = SlackChannel[0]; |
| 27 | + channelID = channelId; |
| 28 | + } catch (err) { |
| 29 | + return res |
| 30 | + .status(400) |
| 31 | + .send({ message: 'incident not found', status: 'failure' }); |
| 32 | + } |
| 33 | + try { |
| 34 | + const chat = await models.SlackWireEvents.create({ |
| 35 | + text: req.body.text, |
| 36 | + type: 'web_message', |
| 37 | + userId: res.locals.currentUser.id, |
| 38 | + channelId: channelID, |
| 39 | + }); |
| 40 | + // post chat to specific slack channel |
| 41 | + postChat |
| 42 | + .postChat(chat.text, channelID) |
| 43 | + .then(response => { |
| 44 | + if (response.ok) { |
| 45 | + return res.status(201).send({ chat, status: 'success' }); |
| 46 | + } |
| 47 | + return res.status(400).send(message); |
| 48 | + }) |
| 49 | + .catch(() => { |
| 50 | + return res.status(400).send(message); |
| 51 | + }); |
| 52 | + } catch (err) { |
| 53 | + res.status(500).send({ |
| 54 | + message: |
| 55 | + 'sorry an error occured. We could not complete your action, try again', |
| 56 | + status: 'failure', |
| 57 | + }); |
| 58 | + } |
| 59 | + }, |
| 60 | +}; |
0 commit comments