diff options
author | eug-vs <eug-vs@keemail.me> | 2020-12-02 02:22:38 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-12-02 02:22:38 +0300 |
commit | 4186fb51f66043b221237c7ba91ac5a95a4f32b0 (patch) | |
tree | 71657f367d899d0fbc165b3c50197d81b8d69007 /lib/model.ts | |
parent | f6c5ac6632781d813a6e1f1ba957e7f9e4d70738 (diff) | |
download | mongo-cronjob-4186fb51f66043b221237c7ba91ac5a95a4f32b0.tar.gz |
feat: add log model
Diffstat (limited to 'lib/model.ts')
-rw-r--r-- | lib/model.ts | 92 |
1 files changed, 0 insertions, 92 deletions
diff --git a/lib/model.ts b/lib/model.ts deleted file mode 100644 index f93928e..0000000 --- a/lib/model.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { model, Schema, Model } from 'mongoose'; -import createEventSchema, { EventDocument } from './schema'; -import cron from 'cron'; - -interface Event<Context> extends EventDocument<Context> { - log(message: string): void; - start(): void; - complete(): void; - fail(error: Error): void; - computeNextRunAt(): Date; -} - -export interface EventModel<Context> extends Model<Event<Context>> { - findNextEvents(): Event<Context>[]; - findMissedEvents(): Event<Context>[]; -} - -const CronJob = cron.CronJob; - -const createEventModel = <Context>(name: string, contextSchema: Schema): EventModel<Context> => { - const schema = createEventSchema(contextSchema); - - // Schema methods - schema.method('log', function(message: string) { - // TODO: Actually create logs - console.log(message); - }); - - schema.method('start', function() { - this.log('Event started') - this.lastRunAt = new Date(); - this.status = 'running'; - return this.save(); - }); - - schema.method('complete', function() { - this.log('Event complete') - this.status = 'complete'; - return this.save(); - }); - - schema.method('fail', function(error: Error) { - this.log(error); - this.error = error; - this.status = 'failed'; - return this.save(); - }); - - schema.method('computeNextRunAt', function() { - const job = new CronJob(this.schedule); - const nextRunAt = job.nextDates(); - return nextRunAt.toDate(); - }); - - // Statics - schema.static('findMissedEvents', async function () { - return this.find({ - nextRunAt: { - // TODO: skip single-fire events - $lt: new Date() - }, - }); - }); - - schema.static('findNextEvents', function(limit = 10) { - return this.find( - { - nextRunAt: { - $gt: new Date() - }, - }, - null, - { - sort: { - nextRunAt: 1 - }, - limit - } - ) - }); - - // Hooks - schema.pre<Event<Context>>('save', async function() { - this.nextRunAt = this.computeNextRunAt(); - }); - - return model<Event<Context>, EventModel<Context>>(name, schema); -}; - - -export default createEventModel; - |