diff --git a/src/middlewares/cooldown.middleware.js b/src/middlewares/cooldown.middleware.js new file mode 100644 index 0000000..7e6fe0b --- /dev/null +++ b/src/middlewares/cooldown.middleware.js @@ -0,0 +1,28 @@ +const { logger } = require('../util/logger'); +const { getSingleBeneficiary } = require('../services/beneficiary.service'); + +async function checkBeneficiaryCooldown(req, res, next) { + const cooldownTime = parseInt( + process.env.BENEFICIARY_COOLDOWN_TIME || '60', + 10 + ); + const customerNo = req.user; + const { toAccount } = req.body; + const beneficiary = await getSingleBeneficiary(customerNo, toAccount); + + if (beneficiary) { + const now = new Date(); + const cooldownPeriod = new Date(now.getTime() - cooldownTime * 60 * 1000); + const createdAt = new Date(beneficiary['created_at']); + if (createdAt > cooldownPeriod) { + const remaining = (now - createdAt) / (60 * 1000); + logger.warn('TRANSACTION_FAILED_BENEFICIARY_COOLDOWN_ACTIVE'); + return res.status(403).json({ + error: `beneficiary cooldown period active. Retry after ${remaining} minutes`, + }); + } + } + next(); +} + +module.exports = { checkBeneficiaryCooldown };