diff options
author | eug-vs <eug-vs@keemail.me> | 2020-11-28 01:11:54 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-11-28 01:11:54 +0300 |
commit | 2a1b70edbdef4ab934d0091a92c14327dde8a256 (patch) | |
tree | 3c77e7fc98f23fc437a641da3a496bdc29c66f42 /src/services/events/event.model.js | |
parent | 86f62a65c4f9ceac086b16fb290544caf2ed1da5 (diff) | |
download | bsu-fantom-2a1b70edbdef4ab934d0091a92c14327dde8a256.tar.gz |
feat: save logs to database
Diffstat (limited to 'src/services/events/event.model.js')
-rw-r--r-- | src/services/events/event.model.js | 48 |
1 files changed, 42 insertions, 6 deletions
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() }, }, |