-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongo.js
117 lines (86 loc) · 2.16 KB
/
mongo.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
* Module Dependencies
*/
var mongoose = require('mongoose');
var mongooseTypes = require('mongoose-types');
mongooseTypes.loadTypes(mongoose, 'email');
/**
* Initalize a new MongoKDb (MongoDB Key Database)
*/
function MongoKDb(url, collectionName) {
this.mongoose = mongoose.connect(url);
var key = mongoose.Schema({
uid: {type:mongoose.SchemaTypes.Email, index: {unique:true}},
domain: {type: String, index: 1},
user: {type: String, index: 1},
keytext: String
});
this.model = this.collection = mongoose.model(collectionName, key);
return this;
}
/**
* Find a single key from the email uid
* @param {String} email Email uid to retrieve a key for
* @param {Function} callback Function to evaluate with the results of the find
*/
MongoKDb.prototype.findOne = function(email, callback) {
this.collection.findOne({uid:email}, callback);
};
/**
* Find all the keys for this server
* @param {String} domain Optional domain in which to search for keys
* @param {Function} callback Function to evaluate with the results of the find
*/
MongoKDb.prototype.find = function(domain, callback) {
var query = {};
if(!callback) {
callback = domain;
domain = null;
}
if(domain) {
query.domain = domain;
}
this.collection.find(query, callback);
};
/**
* Add a key to the database
* @param {String} email Email to associate with the key
* @param {String} keytext ASCII-armored keytext including headers
* @param {Function} callback Function to evaluate with an error or the key on success
*/
MongoKDb.prototype.add = function(email, keytext, callback) {
var parts = email.split('@'),
user = parts[0],
domain = parts[1],
Model = this.model;
this.collection.findOne({uid:email}, function(err, key) {
if(err) {
callback(err);
return;
}
if(!key) {
key = new Model({
uid:email,
domain:domain,
user:user
});
}
key.keytext = keytext;
key.save(function(err, key) {
if(err) {
callback(err);
return;
}
callback(null, {
uid: key.email,
user: user,
domain: domain,
keytext: key.keytext
});
});
});
};
/**
* Export the MongoKDb object
*/
module.exports = MongoKDb;