Skip to content

Instantly share code, notes, and snippets.

@hugdubois
Created May 30, 2012 16:32
Show Gist options
  • Save hugdubois/2837466 to your computer and use it in GitHub Desktop.
Save hugdubois/2837466 to your computer and use it in GitHub Desktop.
Collection = require "../lib/collection"
{_,config,async,Validator,Filter,i18n,errors} = require "smax-utils"
{EValidator} = errors.store
config.store ?= {}
config.store.devices ?= {}
config.store.devices.redis ?= "127.0.0.1:6379": {}
config.store.devices.keyPrefix ?= "devices"
class Devices extends Collection
allowedType: ["android", "ios", "privbot"]
validate: (data, cb) ->
try
[filter, validator] = [new Filter, new Validator]
data[prop] ?= "" for prop in ["type", "uid", "profileId"]
{type, uid, profileId} = data
filter.sanitize(type).toString().trim()
filter.sanitize(uid).toString().trim()
filter.sanitize(profileId).toString().trim()
validator.check(type , param: "type" , msg: i18n("Device type invalid") , value: type ).isIn(@allowedType)
validator.check(uid , param: "uid" , msg: i18n("Device uid invalid") , value: uid ).isMd5()
validator.check(profileId , param: "profileId" , msg: i18n("Device profileId invalid") , value: profileId ).notNull()
errors = validator.getErrors()
return cb new EValidator i18n("Invalid device"), errors unless _.isEmpty errors
cb null, type: type, uid: uid, profileId: profileId
catch e
cb e
insert: (data, cb) ->
@validate data, (err, device) =>
return cb err if err
{type, uid, profileId} = device
_dId = "#{uid}:#{type}"
profileId = data.profileId
async.waterfall [
(next) => @redisClient _dId, next #get deviceId server
(r, key, rId, next) => r.hmset key, profileId: profileId, next #set device hash on deviceId server
(ok, next) => @redisClient type, next #get devices type list server
(r, key, rId, next) => r.sadd key, _dId, next #set device on devices type list server
(ok, next) => @redisClient "all", next #get devices list server
(r, key, rId, next) => r.sadd key, _dId, next #set device on devices list server
], (err, status) => cb err, _dId, status #callback
module.exports = new Devices config.store.devices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment