본문 바로가기
Node.js

[Node.js] 웹훅을 이용하여 Slack 에 메시지 전송하기 - 2. 테스트

by yonikim 2021. 10. 22.
728x90

 

$ npm install axios lodash

 

▷ ./lib/Slack.js

const _ = require('lodash')
const axios = require('axios')

const { SLACK_WEBHOOKS_URL_TEST, AWS_REGION } = process.env

class Slack {
  static get Colors() {
    return {
      primary: '#007bff',
      info: '#17a2b8',
      success: '#28a745',
      warning: '#ffc107',
      danger: '#dc3545',
    }
  }

  static get Channels() {
    return {
      test: `${SLACK_WEBHOOKS_URL_TEST}`,
    }
  }

  static async sendMessage({ header, section, text = '', message, url, functionName }) {
    const data = {
      mrkdwn: true,
      text: text,
      blocks: [],
      attachments: [],
    }
    if (header) {
      const headerBlock = {
        type: 'header',
        text: { type: 'plain_text', text: header, emoji: true },
      }
      data.blocks.push(headerBlock)
    }
    if (section) {
      const sectionBlock = {
        type: 'section',
      }
      if (_.isArray(section)) {
        sectionBlock.fields = section
      }
      if (_.isObject(section)) {
        sectionBlock.text = section
      }
      data.blocks.push(sectionBlock)
    }

    if (message) {
      const lambdaUrl = `https://${AWS_REGION}.aws.amazon.com/lambda/home?region${AWS_REGION}#/functions/${functionName}`
      message.ts = Math.floor(Date.now() / 1000)
      message.footer = `From [<${lambdaUrl}|${functionName}>]`
      data.attachments.push(message)
    }

    console.log(JSON.stringify(data))

    axios({
      url,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data,
    })
  }
}

module.exports = Slack

 

▷ lambdaTest.js

const { Colors, Channels, sendMessage } = require('./lib/slack')

const CHANNEL_NAME = 'test'
const START_TIME = new Date().getTime()

const handler = async (event, context) => {
  const url = Channels[CHANNEL_NAME]
  const { functionName } = context
  try {
    if (!functionName) throw { message: `functionName 이 없습니다.` }

    const lapTime = new Date().getTime() - START_TIME
    const header = 'SLACK 메시지 보내기 성공 :large_green_circle:'

    const message = {
      color: Colors.success,
      title: `SLACK 메시지`,
      text: `HELLO, SLACK!! 수행시간: ${lapTime}ms`,
    }
    await sendMessage({ header, message, url, functionName })
  } catch (err) {
    const { title, message: text } = err
    const header = 'SLACK 메시지 보내기 실패 :x:'
    const message = {
      color: Colors.danger,
      title,
      text,
    }
    await sendMessage({ header, message, url, functionName })
  }
}
;(async () => {
  try {
    const event = {}
    const context = {
      functionName: 'service-stage-functionName', // 이 부분으로 주석처리 유무로 테스트
    }

    await handler(event, context)
  } catch (err) {
    console.log(err)
  }
})()

 

context.functionName 주석처리 유무로 해당 함수가 성공했을 때와 에러가 발생했을 때의 메시지 샘플을 확인해 보자.

$ node lambdaTest.js

 

728x90