aboutsummaryrefslogtreecommitdiffhomepage
path: root/models/poolRequests.js
blob: 962e75e6a5bab36fac95e95c7073e5afc07a9df4 (plain) (blame)
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
65
66
67
68
69
70
71
72
73
74
;(function () {
  'use strict'

  var mongoose = require('mongoose')

  var logger = require('../helpers/logger')

  // ---------------------------------------------------------------------------

  var poolRequestsSchema = mongoose.Schema({
    type: String,
    id: String, // Special id to find duplicates (video created we want to remove...)
    request: mongoose.Schema.Types.Mixed
  })
  var PoolRequestsDB = mongoose.model('poolRequests', poolRequestsSchema)

  // ---------------------------------------------------------------------------

  var PoolRequests = {
    addRequest: addRequest,
    list: list,
    removeRequests: removeRequests
  }

  function addRequest (id, type, request) {
    logger.debug('Add request to the pool requests.', { id: id, type: type, request: request })

    PoolRequestsDB.findOne({ id: id }, function (err, entity) {
      if (err) {
        logger.error('Cannot find one pool request.', { error: err })
        return // Abort
      }

      if (entity) {
        if (entity.type === type) {
          logger.error('Cannot insert two same requests.')
          return // Abort
        }

        // Remove the request of the other type
        PoolRequestsDB.remove({ id: id }, function (err) {
          if (err) {
            logger.error('Cannot remove a pool request.', { error: err })
            return // Abort
          }
        })
      } else {
        PoolRequestsDB.create({ id: id, type: type, request: request }, function (err) {
          logger.error('Cannot create a pool request.', { error: err })
          return // Abort
        })
      }
    })
  }

  function list (callback) {
    PoolRequestsDB.find({}, { _id: 1, type: 1, request: 1 }, callback)
  }

  function removeRequests (ids) {
    PoolRequestsDB.remove({ _id: { $in: ids } }, function (err) {
      if (err) {
        logger.error('Cannot remove requests from the pool requests database.', { error: err })
        return // Abort
      }

      logger.info('Pool requests flushed.')
    })
  }

  // ---------------------------------------------------------------------------

  module.exports = PoolRequests
})()