-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.datastore.js
102 lines (92 loc) · 2.53 KB
/
lib.datastore.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var mysql = require('mysql');
var http = require('http');
var fs = require('fs');
var mongodb = require('mongodb');
var qs = require('querystring');
var _ = require('underscore');
function datastore(options) {
this.options = _.extend({
host: "127.0.0.1",
port: 27017,
database: "fleetwit"
},options);
this.collections = {};
}
datastore.prototype.init = function(callback) {
var scope = this;
this.server = new mongodb.Server(this.options.host, this.options.port, {});
this.db = new mongodb.Db(this.options.database, this.server, {w:1});
this.db.open(function (error, client) {
if (error) {
throw error;
}
scope.instance = client;
callback();
});
}
datastore.prototype.open = function(collectionName, callback) {
var scope = this;
if (!this.collections[collectionName]) {
this.collections[collectionName] = new mongodb.Collection(this.instance, collectionName);
}
callback(this.collections[collectionName]);
}
datastore.prototype.getUser = function(collectionName, uid, callback) {
var scope = this;
this.open(collectionName, function(collection) {
collection.find({
uid: uid
}, {
limit:1
}).toArray(function(err, docs) {
console.dir(docs);
if (docs.length == 0) {
// No userdata, we create it.
collection.insert({
uid: uid,
surveydata: {},
facebookdata: {},
twitterdata: {}
}, function(err, docs) {
callback(collection);
});
} else {
callback(collection);
}
});
});
}
datastore.prototype.set = function(collection, label, value, callback) {
var scope = this;
var criteria = {};
criteria[label] = label;
var buffer = {};
buffer.value = value;
collection.update(criteria, {$set: buffer}, {upsert:true}, callback);
}
datastore.prototype.incr = function(collection, criteria, value, callback) {
var scope = this;
var buffer = {};
buffer.value = value;
collection.findAndModify(criteria, [['_id','asc']], {$set:{updated:true}, $inc: {value: value}}, {}, function(err, data) {
if (err) {
// couldn't update, let's create
collection.update(_.extend({value:value},criteria), {$set: buffer}, {upsert:true}, function(err2, data2) {
scope.get(collection, criteria, function(err3, data3) {
callback(data3)
});
});
} else {
callback(data);
}
});
}
datastore.prototype.get = function(collection, label, callback) {
var scope = this;
var criteria = {};
criteria[label] = label;
collection.findOne(criteria, function(err, data) {
callback(data);
});
}
exports.datastore = datastore;