在 Egg.js 中,可以使用定时任务模块实现发送验证码后自动更新对应邮箱的验证码状态。

首先,在 config/config.default.js 中配置定时任务模块:

// config/config.default.js

exports.schedule = {
  enable: true,
  cron: '0 0 */1 * * *', // 每小时执行一次
};

然后,在 app/schedule 目录下新建一个定时任务文件 verifyCodeUpdate.js,实现根据 email 查找并更新验证码状态的逻辑:

// app/schedule/verifyCodeUpdate.js

module.exports = {
  async task(ctx) {
    const { email } = ctx;
    const result = await ctx.model.User.update({ email, verifyCodeStatus: 0 }, { where: { email } });
    console.log(`update verify code status for email ${email}: ${result}`);
  },
};

在发送验证码的方法中,调用定时任务模块的 scheduleTask 方法,执行验证码状态更新任务:

// app/controller/verifyCode.js

class VerifyCodeController extends Controller {
  async send() {
    const { ctx } = this;
    const { email } = ctx.request.body;
    const verifyCode = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    const result = await ctx.service.verifyCode.send(email, verifyCode);
    if (result) {
      // 发送验证码成功后手动调用定时任务,传入email参数
      ctx.app.runSchedule('verifyCodeUpdate', { email });
      ctx.body = { success: true };
    } else {
      ctx.body = { success: false };
    }
  }
}

这样,在发送验证码成功后,就会自动执行一次定时任务,更新该 email 的验证码状态为 0。

注意:

  • 以上代码示例仅供参考,实际代码可能需要根据具体需求进行调整。
  • 在实际开发中,建议使用更加可靠的定时任务方案,例如使用第三方服务或数据库定时器。
  • 建议对验证码状态进行有效期管理,防止恶意攻击。
  • 确保 verifyCodeStatus 字段在数据库中的正确定义和使用。
  • 确保 runSchedule 方法在代码中正确使用和配置。
  • 请务必保证代码的安全性,防止恶意攻击和数据泄露。
Egg.js 发送验证码后执行一次性定时任务更新验证码状态

原文地址: https://www.cveoy.top/t/topic/npp2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录