summaryrefslogtreecommitdiff
path: root/src/services/events/event.service.js
blob: 6c0454e035d94a57bc3123b9e832606feda6067e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const { Types } = require('mongoose');
const { Service } = require('feathers-mongoose');
const _ = require('lodash');
const cron = require('cron');

const Model = require('./event.model.js');
const handleAttendClassJob = require('../../handlers');
const CronJob = cron.CronJob;

class Events extends Service {
  async setup(app, path) {
    await this.Model.rescheduleOldEvents();
    const fetchNextEvent = () => this.fetchNextEvent();
    this.fetchEventJob = new CronJob('*/10 * * * * *', fetchNextEvent);
    this.fetchEventJob.start()
  }

  async fetchNextEvent() {
    const event = await this.Model.findNextEvent();

    if (event) {
      this.log(`Found an upcoming event: ${event.name}`);
      if (this.nextJob) this.nextJob.stop();
      this.nextJob = new CronJob(event.schedule, () => this.process(event._id))
      this.nextJob.start()
    } else this.log('No upcoming events.');
  }

  log(message) {
    const dateOpts = { timeStyle: 'medium', dateStyle: 'short' };
    const timestamp = new Date().toLocaleString('en', dateOpts);
    return console.log(`[${timestamp}] ${message}`);
  }

  async process(id) {
    const event = await this.Model.findById(id);
    this.log(`Running event ${event.name}`);
    event.status = 'running';
    await event.save();
    await this.fetchNextEvent();
    try {
      // await handleAttendClassJob(event);
      await new Promise(res => {
        console.log('Job started')
        setTimeout(() => {
          console.log('Job ended')
          res();
        }, 10000)
      });
    } catch (error) {
      event.status = 'failed';
    }
    if (event.status === 'running') {
      event.status = 'complete';
      event.save();
    }
  }
}


module.exports = app => {
  app.use('/events', new Events({ Model }));
};