All files / src polling.coffee

46.43% Statements 13/28
100% Branches 0/0
0% Functions 0/8
46.43% Lines 13/28
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 541x 1x 1x 1x 1x 1x 1x 1x 1x   1x   1x                                           1x           1x                          
Channels = require('./model/channels')
Channel = Channels.Channel
request = require 'request'
config = require './config/config'
config.polling = config.get('polling')
logger = require 'winston'
Q = require 'q'
authorisation = require './middleware/authorisation'
utils = require './utils'
 
exports.agendaGlobal = null
 
exports.registerPollingChannel = (channel, callback) ->
  logger.info "Registering polling channel: #{channel._id}"
  return callback new Error 'no polling schedule set on this channel' if not channel.pollingSchedule
 
  exports.agendaGlobal.cancel { name: "polling-job-#{channel._id}" }, (err) ->
    return callback err if err
    exports.agendaGlobal.define "polling-job-#{channel._id}", (job, done) ->
      logger.info "Polling channel #{channel._id}"
 
      options =
        url: "http://#{config.polling.host}:#{config.polling.pollingPort}/trigger"
        headers:
          'channel-id': channel._id
          'X-OpenHIM-LastRunAt': job.attrs.lastRunAt
 
      request options, ->
        done()
 
    exports.agendaGlobal.every channel.pollingSchedule, "polling-job-#{channel._id}", null, { timezone: utils.serverTimezone() }
 
    callback null
 
exports.removePollingChannel = removePollingChannel = (channel, callback) ->
  logger.info "Removing polling schedule for channel: #{channel._id}"
  exports.agendaGlobal.cancel { name: "polling-job-#{channel._id}" }, (err) ->
    return callback err if err
    callback null
 
exports.setupAgenda = (agenda, callback) ->
  logger.info "Starting polling server..."
  registerPollingChannelPromise = Q.denodeify exports.registerPollingChannel
  exports.agendaGlobal = agenda
  Channel.find { type: 'polling' }, (err, channels) ->
    return err if err
 
    promises = []
    for channel in channels
      if Channels.isChannelEnabled channel
        promises.push registerPollingChannelPromise channel
 
    (Q.all promises).done callback