All files / src utils.coffee

44.44% Statements 16/36
9.09% Branches 1/11
0% Functions 0/11
47.06% Lines 16/34
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 721x 1x 1x 1x 1x 1x     1x           1x   1x   1x                                                                     1x   1x     1x     1x           1x     1x  
logger = require 'winston'
config = require './config/config'
config.caching = config.get('caching')
Channel = require("./model/channels").Channel
Keystore = require("./model/keystore").Keystore
momentTZ = require 'moment-timezone'
 
# function to log errors and return response
exports.logAndSetResponse = (ctx, status, msg, logLevel) ->
  logger[logLevel] msg
  ctx.body = msg
  ctx.status = status
 
 
cacheValueStore = {}
 
refreshMillis = config.caching.refreshMillis
 
getCachedValues = (store, callback) ->
  lastCheck = cacheValueStore["#{store}"]?.lastCheck
 
  if not config.caching.enabled or not lastCheck? or ((new Date)-lastCheck) > refreshMillis
 
    handler = (err, results) ->
      return callback err if err
 
      if config.caching.enabled
        if not lastCheck then cacheValueStore["#{store}"] = {}
        cacheValueStore["#{store}"].value = results
        cacheValueStore["#{store}"].lastCheck = new Date
 
      callback null, results
 
    #TODO make this more generic (had issues passing Channel.find as a param [higher order function])
    if store is 'channels'
      Channel.find({}).sort(priority: 1).exec (err, channels) ->
        return handler err if err
        noPriorityChannels = []
        sortedChannels = []
        channels.forEach (channel) ->
          if not channel.priority?
            noPriorityChannels.push channel
          else
            sortedChannels.push channel
        handler null, sortedChannels.concat(noPriorityChannels)
    else if store is 'keystore'
      Keystore.findOne {}, handler
    else
      callback "Internal error: Invalid store #{store}"
 
  else
    callback null, cacheValueStore["#{store}"].value
 
exports.getAllChannelsInPriorityOrder = (callback) -> getCachedValues 'channels', callback
 
exports.getKeystore = (callback) -> getCachedValues 'keystore', callback
 
# function to check if string match status code pattern
exports.statusCodePatternMatch = (string, callback) -> /\dxx/.test string
 
# returns an array with no duplicates
exports.uniqArray = (arr) ->
  dict = {}
  dict[k] = k for k in arr
  return (v for k, v of dict)
 
# thanks to https://coffeescript-cookbook.github.io/chapters/arrays/check-type-is-array
exports.typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
 
# get the server timezone
exports.serverTimezone = () ->
  return momentTZ.tz.guess()