From ec2f803a306c7843a8814029b5e77a9dadffd136 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Thu, 30 Jun 2011 23:48:38 +0200 Subject: progress: templates/css, new router, paste module as db abstraction --- lib/paste.js | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 lib/paste.js (limited to 'lib/paste.js') diff --git a/lib/paste.js b/lib/paste.js new file mode 100644 index 0000000..a60bee2 --- /dev/null +++ b/lib/paste.js @@ -0,0 +1,68 @@ +var kyoto = require('kyoto'), +uuid = require(__dirname + '/uuid'); + +var db; + +var generateId = function(callback) { + var id = uuid.generate(14); + + db.get(id, function(err, value) { + if (value) { + generateId(); + } + else { + callback(id); + } + }); +}; + +var get = function(id, callback) { + db.get(id, function(err, value) { + if (value) { + value = JSON.parse(value); + } + + callback(value); + }); +}; + +var add = function(post, callback) { + generateId(function(id) { + var data = { + content: post.content, + language: post.language, + time: new Date() + }; + + db.set(id, JSON.stringify(data), function(err) { + callback(err, id); + }); + }); +}; + +var init = function(config, callback) { + db = new kyoto.open(config.database, 'a+', function(err) { + if (err) throw err; + + process.on('uncaughtException', function(exeption) { + console.error('%j', exeption); + process.exit(1); + }); + + process.on('exit', function() { + db.close(function(err) { console.log(err); }); + }); + + var thismodule = { + get: get, + add: add + }; + + callback(thismodule); + + }); +}; + +module.exports = { + init: init +}; -- cgit v1.2.3