Browse files

add id generator

  • Loading branch information...
1 parent b55660c commit 1d060b83f5fdc28a14bd2753f832357f43e84dc8 @stliu committed Jan 30, 2014
Showing with 43 additions and 1 deletion.
  1. +8 −0 lib/api.coffee
  2. +23 −0 lib/idgenerator.coffee
  3. +2 −1 package.json
  4. +10 −0 pushd.coffee
View
8 lib/api.coffee
@@ -185,3 +185,11 @@ exports.setupRestApi = (app, createSubscriber, getEventFromId, testSubscriber, e
res.send 204
else
res.send 404
+
+ app.get '/id/:gen_key', (req, res) ->
+ req.generator.gen (err, value)->
+ if err
+ res.json err, 400
+ else
+ res.json value, 200
+
View
23 lib/idgenerator.coffee
@@ -0,0 +1,23 @@
+random = require('secure_random');
+
+class Generator
+ start = 10000;
+ end = 9999999;
+
+ constructor: (@redis, @key) ->
+
+ gen: (cb) =>
+ random.getRandomInt start, end, (e1, value) =>
+ if e1?
+ cb(e1)
+ else
+ @redis.setbit @key, (value - start), 1, (e2, exist)->
+ if e2?
+ cb(e2)
+ else
+ if(exist == 0)
+ cb(null, value)
+ else
+ gen(cb)
+
+exports.Generator = Generator
View
3 package.json
@@ -47,7 +47,8 @@
"winston": "~0.6.2",
"junction": "*",
"node-xmpp": "~0.6.3",
- "generate-key": "0.0.6"
+ "generate-key": "0.0.6",
+ "secure_random": "~0.1.0"
},
"devDependencies": {
"mocha": "*",
View
10 pushd.coffee
@@ -11,6 +11,7 @@ Event = require('./lib/event').Event
Application = require('./lib/app').App
PushServices = require('./lib/pushservices').PushServices
Payload = require('./lib/payload').Payload
+Generator = require('./lib/idgenerator').Generator
logger = require 'winston'
sys = require 'sys'
@@ -120,6 +121,15 @@ rest_server.param 'event_id', (req, res, next, id) ->
catch error
res.json error: error.message, 400
+rest_server.param 'gen_key', (req, res, next, id) ->
+ try
+
+ req.generator = new Generator(redis, "generator:#{req.params.gen_key}")
+ delete req.params.gen_key
+ next()
+ catch error
+ res.json error: error.message, 400
+
rest_server.param 'jid', (req, res, next, id) ->
try
getSubscriberFromJid req.application.id, req.params.jid, (subscriber)->

0 comments on commit 1d060b8

Please sign in to comment.