const cron = require('cron'); const { model } = require('mongoose'); const schema = require('./event.schema.js'); const CronJob = cron.CronJob; schema.methods.computeNextRunAt = function() { const job = new CronJob(this.schedule); const nextRunAt = job.nextDates(); return new Date(nextRunAt); }; schema.methods.setStatus = function(status) { this.status = status;; this.save(); }; schema.pre('save', function(next) { this.nextRunAt = this.computeNextRunAt(); next(); }); schema.statics.findMissedEvents = async function () { return this.find({ nextRunAt: { // TODO: skip single-fire events $lt: new Date() }, }); }; schema.statics.findNextEvents = function(limit = 10) { return this.find( { nextRunAt: { $exists: 1, $gt: new Date() }, }, null, { sort: { nextRunAt: 1 }, limit } ) }; const Model = model('Event', schema); module.exports = Model;