From 2a1b70edbdef4ab934d0091a92c14327dde8a256 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sat, 28 Nov 2020 01:11:54 +0300 Subject: feat: save logs to database --- src/services/events/event.model.js | 48 +++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 6 deletions(-) (limited to 'src/services/events/event.model.js') diff --git a/src/services/events/event.model.js b/src/services/events/event.model.js index b8a13bc..9ecacb7 100644 --- a/src/services/events/event.model.js +++ b/src/services/events/event.model.js @@ -1,20 +1,57 @@ const cron = require('cron'); const { model } = require('mongoose'); const schema = require('./event.schema.js'); +const LogModel = require('./log.model.js'); const CronJob = cron.CronJob; +schema.methods.log = function(message) { + const dateOpts = { timeStyle: 'medium', dateStyle: 'short' }; + const timestamp = new Date().toLocaleString('en', dateOpts); + console.log(`[${timestamp}] ${this.name}: ${message}`); + + return LogModel.create({ + eventId: this._id, + message + }); +}; + +schema.methods.start = function() { + this.log('Event started') + this.lastRunAt = new Date(); + this.status = 'running'; + return this.save(); +}; + +schema.methods.complete = function() { + this.log('Event complete') + this.status = 'complete'; + return this.save(); +}; + +schema.methods.fail = function(error) { + this.log(error); + this.error = error; + this.status = 'failed'; + return this.save(); +}; + +schema.methods.run = async function(handler) { + try { + this.start(); + await handler(this); + return this.complete(); + } catch (error) { + this.fail(error); + } +}; + 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(); @@ -33,7 +70,6 @@ schema.statics.findNextEvents = function(limit = 10) { return this.find( { nextRunAt: { - $exists: 1, $gt: new Date() }, }, -- cgit v1.2.3