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

Stop a module initialising on import in Javascript

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

我有这个作为我的通知功能:

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 获取松弛令牌)。

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

我非常坚持这一点,认为我可能需要重构为 class?欢迎任何建议!

只是懒惰地初始化一个实例:

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
}

但是,您的环境变量应该始终在进程启动时已经存在,或者至少在使用的模块之前由dotenv之类的内容填充他们被加载了。