summaryrefslogtreecommitdiff
path: root/examples/lib/okpush/db.js
blob: 67d1ba87b8370e568bdd729138da691b96edfac2 (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
var mongoose = require('mongoose')
var _ = require('lodash')
var db, PushToken

function init (config) {
  db = mongoose.connect(config.mongodbUrl)
  mongoose.connection.on('error', errorHandler)

  var pushTokenSchema = new db.Schema({
    type: {
      type: 'String',
      required: true,
      enum: ['ios', 'android'],
      lowercase: true,
    },
    token: {
      type: 'String',
      required: true,
    }
  })

  PushToken = db.model('PushToken', pushTokenSchema)
}

function errorHandler (error) {
  console.error('ERROR: ' + error)
}
function add (deviceType, token) {
  var pushItem = new PushToken({ type: deviceType, token: token })
  pushItem.save()
}
function getAll (cb) {
  var wcb = wrap(cb)
  PushToken.find(wcb)
}
function removeDevice () {
  PushToken.remove({token: token}, function (err) {
      if (err) console.log(err)
  })
}
function removeDevices (tokens) {
  PushAssociation.remove({token: {$in: tokens}}, function (err) {
    if (err) console.log(err)
  })
}
function wrap (cb) {
  return function (err, items) {
    if (err) return cb(err, null)

    var items = _.map(items, function (item) {
      return _.pick(item, ['type', 'token'])
    })

    return callback(null, items)
  }
}
module.exports = {
  init: init,
  add: add,
  getAll: getAll,
  removeDevice: removeDevice,
  removeDevices: removeDevices,
}