how to use cron job in node js code example
Example: nodejs cronjob
const cron = require('node-schedule')
const axios = require('axios')
const IpAddress = []
const IpGeolocation = async () => {
const ip = {}
const res = await axios.get('http://ipwhois.app/json/')
Object.defineProperty(ip, 'ipv4', { value: res.data.ip, enumerable: true })
return ip.ipv4
}
const ResetRateLimit = () => {
const schedule = new cron.RecurrenceRule()
schedule.second = 59
schedule.tz = 'asia/jakarta'
cron.scheduleJob('ResetRateLimit', schedule, () => {
IpAddress.splice(0, IpAddress.length)
})
}
module.exports = async (req, res, next) => {
const myIp = await IpGeolocation()
switch (req.method) {
case 'GET':
if (IpAddress.length < 7) {
IpAddress.push(myIp)
}
break
case 'POST':
if (IpAddress.length < 7) {
IpAddress.push(myIp)
}
break
default:
return next()
}
const currentIp = IpAddress.filter((v, i) => v === myIp).length
if (currentIp > 4) {
return res.status(401).json({
method: req.method,
status: res.statusCode,
error: 'Oopss..request method not allowed many to request'
})
}
ResetRateLimit()
return next()
}