停止在Java中导入时初始化的模块

问题描述 投票:0回答:1

我正在处理通知包,但在如何新建一个函数时遇到了一些麻烦,而不仅仅是在导入时遇到了麻烦。例如:

我将此作为通知功能:

const sendNotification = async (options: SendNotificationTypes) => {
  const handleChannel = {
    slack: async (options: SlackNotificationTypes) => {
      await sendSlack(options);
    },
    email: async (options: EmailNotificationTypes) => {
      await sendEmail(options);
    },
    sms: async (options: SMSNotificationTypes) => {
      await sendSms(options);
    }
  };

  options.channels.forEach(channel => {
    switch (channel) {
      case CHANNEL_SLACK:
        handleChannel.slack(options.slack);
        break;
      case CHANNEL_EMAIL:
        handleChannel.email(options.email);
        break;
      case CHANNEL_SMS:
        handleChannel.sms(options.sms);
        break;
    }
  });
};

我的松弛通知程序看起来像这样:


const slack = new WebClient(tokenGoesHere)

const sendSlack = async (options: SlackNotificationTypes) => {
  try {
    await slack.chat.postMessage({
      channel: options.channel,
      ...(options.message && { text: options.message }),
      ...(options.blocks && { blocks: options.blocks }),
      ...(options.emoji && { icon_emoji: options.emoji }),
      ...(options.attachments && {
        attachments: options.attachments
      })
    });
  } catch (error) {
    throw new Error(`Slack notification failed to send: ${error}`);
  }
};

因此,这很好,但是如果我的环境变量不到位,代码就会在某些地方失败(因为我是从process.env采购松弛令牌)。

相反,我希望能够在需要时实例化该函数,并在那时传递松弛令牌。理想情况下,如果有一种方法每次我发送通知时都不需要新实例,那么我想这样做。

我对此很固执,认为我可能需要重构为一堂课?欢迎任何建议!

javascript node.js slack
1个回答
0
投票

只是延迟初始化一个实例:

let slack = null; // token not yet available

async function sendSlack(options: SlackNotificationTypes) {
    if (!slack) {
        slack = new WebClient(tokenGoesHere) // hopefully available now
    }
    … // rest of the code using `slack` instance
}

但是,在启动过程时,您的环境变量应该always已经存在,或者至少在加载使用它们的模块之前用dotenv之类的东西填充。

© www.soinside.com 2019 - 2024. All rights reserved.