Unable to read the value from ssm using middy in nodejs

358 views Asked by At

Can someone help me with below code issue, For some reason. Lambda is giving me error

Log:

{ "errorType": "TypeError", "errorMessage": "Cannot read properties of undefined (reading 'Parameter')", "stack": [ "TypeError: Cannot read properties of undefined (reading 'Parameter')", " at /var/task/index.js:15922:46", " at runMiddlewares (/var/task/index.js:15555:23)", " at async runRequest (/var/task/index.js:15513:5)" ] }

Environment variable is set correctly, if i am hard coding the bot token here the code is working.

    // Require the Node Slack SDK package (github.com/slackapi/node-slack-sdk)
const { WebClient, LogLevel } = require("@slack/web-api");
import middy from '@middy/core'
import ssm from '@middy/ssm'
import doNotWaitForEmptyEventLoop from '@middy/do-not-wait-for-empty-event-loop'

const { BOT_TOKEN } = process.env;

if (!BOT_TOKEN) {
  throw new Error("BOT_TOKEN environment variable is not set");
}

let slackClient;
function initializeClient(botToken) {
  // WebClient instantiates a client that can call API methods
  // When using Bolt, you can use either `app.client` or the `client` passed to listeners.
  if (slackClient == undefined) {
    slackClient = new WebClient(botToken, {
      // LogLevel can be imported and used to make debugging simpler
      logLevel: LogLevel.DEBUG
    });
  }
  return slackClient;
}

const sendSlackNotification = async (message) => {
  const response = await slackClient.chat.postMessage({
    channel: process.env.SLACK_CHANNEL,
    text: message,
  });


  console.log(`Slack response: ${JSON.stringify(response)}`);
};

async function handlePipelineEvent(event) {
  console.log(`Event: ${JSON.stringify(event)}`);
 
  const { detail } = event;
  const pipeline = detail.pipeline;
  const stage = detail.stage;
  const state = detail.state;

  let message;
  switch (state) {
    case "STARTED":
      message = `:Pipeline \`${pipeline}\` has started executing stage \`${stage}\``;
      break;
   
    default:
      message = `Pipeline ${pipeline} has changed state to ${state} on stage ${stage}`;
  }

  await sendSlackNotification(message);
  console.log('3');
  return {
    statusCode: 200,
    body: JSON.stringify("Slack notification sent successfully"),
  };
};

export const handler = middy(handlePipelineEvent).use(ssm({
  cache: true,
  cacheExpiryInMillis: 5 * 60 * 1000, // 5 minutes
  setToContext: true,
  names: {
    botToken: process.env.BOT_TOKEN
  }
})).before(async (handler) => {
  const botToken = handler.context.botToken.Parameter.Value;
  console.log(`Retrieved bot token: ${botToken}`);
  initializeClient(botToken);
}); 
0

There are 0 answers