aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/requests.js
blob: e67ccad56420124111311fb15770303722b9739d (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
'use strict'

const mongoose = require('mongoose')

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

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

const requestsSchema = mongoose.Schema({
  request: mongoose.Schema.Types.Mixed,
  to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'users' } ]
})
const RequestsDB = mongoose.model('requests', requestsSchema)

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

const Requests = {
  create: create,
  findById: findById,
  list: list,
  removeAll: removeAll,
  removePodOf: removePodOf,
  removeRequestById: removeRequestById,
  removeRequests: removeRequests,
  removeWithEmptyTo: removeWithEmptyTo
}

function create (request, to, callback) {
  RequestsDB.create({ request: request, to: to }, callback)
}

function findById (id, callback) {
  RequestsDB.findOne({ id: id }, callback)
}

function list (callback) {
  RequestsDB.find({}, { _id: 1, request: 1, to: 1 }, callback)
}

function removeAll (callback) {
  RequestsDB.remove({ }, callback)
}

function removePodOf (requestsIds, podId, callback) {
  if (!callback) callback = function () {}

  RequestsDB.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
}

function removeRequestById (id, callback) {
  RequestsDB.remove({ id: id }, callback)
}

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

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

function removeWithEmptyTo (callback) {
  if (!callback) callback = function () {}

  RequestsDB.remove({ to: { $size: 0 } }, callback)
}

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

module.exports = Requests