我在nodejs上有一个api构建。收到一个用户的第一个请求后,我想触发一个发送电子邮件功能,该功能在15分钟后发送邮件。但是,如果在这15分钟内对同一用户发出了新请求,我想关闭以前的计时器,并从15分钟后重新启动计数器。
我面临的问题是如何检查以前是否已对api进行过任何调用。
我想到的一种可能的解决方案是在db中存储一个标志,并在每个api调用上进行更新,这将告诉用户是否已触发sendEmail。但是也许我可以,尽管在运行时使用一个变量来存储以前的状态也可能实现。有可能这样做吗?
假设您为每个用户都有一些唯一的标识符。然后,您可以仅创建一个Map
以userID作为键的对象,而数据的对象则包含一个计时器作为值。
const userEmailData = new Map();
function sendUserEmailWithDelay(userId, emailContent) {
let userData = userEmailData.get(userId);
// if existing userData, then clear existing timer
if (userData) {
clearTimeout(userData.timer);
}
// set new timer for 15 minutes from now
userData = {userId, emailContent, timer};
let timer = setTimeout(() => {
// remove our object from the Map
userEmailData.delete(userId);
// send the email here using userData to know what to send and to whom
}, 15 * 60 * 1000);
// put this userData object into the Map
userEmailData.set(userId, userData);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句