-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
383 lines (318 loc) · 9.03 KB
/
index.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright Peter Širka, Web Site Design s.r.o. (www.petersirka.sk)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var urlParser = require('url');
var http = require('http');
var https = require('https');
/*
MongoDB class
@database {String}
@key {String} :: get your key from https://mongolab.com/user?username=[username]
*/
function MongoDB(database, key) {
this.key = key;
this.database = database;
this.uri = urlParser.parse('https://api.mongolab.com/api/1/databases/');
};
// ======================================================
// FUNCTIONS
// ======================================================
/*
Check if string is JSON object
@value {String}
return {Object}
*/
function parseJSON(value) {
if (isJSON(value))
return JSON.parse(value);
return {};
};
function isJSON(value) {
if (value.length === 1)
return false;
var a = value[0];
var b = value[value.length - 1];
return (a === '"' && b === '"') || (a === '[' && b === ']') || (a === '{' && b === '}');
};
/*
Object to URL params
@obj {Object}
return {String}
*/
function toParams(obj, key) {
if (typeof(obj) === 'undefined' || obj === null)
return '?apiKey=' + key;
var buffer = [];
var arr = Object.keys(obj);
arr.forEach(function(o) {
var value = obj[o];
var name = o.toLowerCase().replace(/-/g, '');
switch (name) {
case 'q':
case 'query':
case 'where':
buffer.push('q=' + encodeURIComponent(JSON.stringify(value)));
break;
case 'include':
if (typeof(value) === 'array') {
var prepare = {};
value.forEach(function(o) {
prepare[o] = 1;
});
value = prepare;
}
buffer.push('f=' + encodeURIComponent(JSON.stringify(value)));
break;
case 'exclude':
if (typeof(value) === 'array') {
var prepare = {};
value.forEach(function(o) {
prepare[o] = 0;
});
value = prepare;
}
buffer.push('f=' + encodeURIComponent(JSON.stringify(value)));
break;
case 'f':
buffer.push('f=' + encodeURIComponent(JSON.stringify(value)));
break;
case 'l':
case 'max':
case 'top':
case 'limit':
case 'take':
buffer.push('l=' + value);
break;
case 'skip':
case 'sk':
buffer.push('sk=' + value);
break;
case 'asc':
if (typeof(value) === 'array') {
var prepare = {};
value.forEach(function(o) {
prepare[o] = 1;
});
value = prepare;
}
buffer.push('s=' + encodeURIComponent(JSON.stringify(value)));
break;
case 'desc':
if (typeof(value) === 'array') {
var prepare = {};
value.forEach(function(o) {
prepare[o] = -1;
});
value = prepare;
}
buffer.push('s=' + encodeURIComponent(JSON.stringify(value)));
break;
case 's':
case 'sort':
case 'sorting':
buffer.push('s=' + encodeURIComponent(JSON.stringify(value)));
break;
case 'c':
case 'count':
buffer.push('c=' + value.toString().toLowerCase());
break;
case 'fo':
case 'first':
buffer.push('fo=' + value.toString().toLowerCase());
break;
case 'm':
case 'updateall':
case 'all':
buffer.push('m=' + value.toString().toLowerCase());
break;
case 'u':
case 'upsert':
buffer.push('u=' + value.toString().toLowerCase());
break;
default:
break;
};
});
var params = buffer.join('&');
return '?' + (params.length > 0 ? params + '&' : '') + 'apiKey=' + key;
};
// ======================================================
// PROTOTYPES
// ======================================================
/*
Internal function
@path {String}
@method {String}
@data {String or Object or Array}
@params {Object}
@callback {Function} :: function(error, object)
return {self}
*/
MongoDB.prototype.connect = function(path, method, data, params, callback) {
var self = this;
if (path[0] === '/')
path = path.substring(1);
var uri = self.uri;
var type = typeof(data);
var isObject = type === 'object' || type === 'array';
var headers = {};
headers['Content-Type'] = isObject ? 'application/json' : 'text/plain';
var location = '';
if (path[0] === '#')
location = path.substring(1);
else
location = uri.pathname + path;
var options = { protocol: uri.protocol, auth: uri.auth, method: method || 'GET', hostname: uri.hostname, port: uri.port, path: location + toParams(params, self.key), agent:false, headers: headers };
var response = function (res) {
var buffer = '';
res.on('data', function(chunk) {
buffer += chunk.toString('utf8');
})
req.setTimeout(exports.timeout, function() {
callback(new Error('timeout'), null);
});
res.on('end', function() {
var data = parseJSON(buffer.trim());
var error = null;
if (res.statusCode > 200) {
error = new Error(res.statusCode + ' (' + (data.message || '') + ') ');
data = null;
}
callback(error, data);
});
};
var con = options.protocol === 'https:' ? https : http;
var req = callback ? con.request(options, response) : con.request(options);
req.on('error', function(err) {
callback(err, null);
});
if (isObject)
req.end(JSON.stringify(data));
else
req.end();
return self;
};
/*
MongoDB command
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.collections = function(cb) {
var self = this;
return self.connect(self.database + '/collections/', 'GET', null, null, cb);
};
/*
MongoDB command
@collection {String}
@params {Object}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.documents = function(collection, params, cb) {
var self = this;
return self.connect(self.database + '/collections/' + collection + '/', 'GET', null, params, cb);
};
/*
MongoDB command
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.databases = function(cb) {
return this.connect('', 'GET', null, null, cb);
};
/*
MongoDB command
@collection {String}
@documents {Object or Object array}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.insert = function(collection, documents, cb) {
var self = this;
return self.connect(self.database + '/collections/' + collection + '/', 'POST', documents, null, cb);
};
/*
MongoDB command
@collection {String}
@condition {Object or Object array}
@params {Object}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.update = function(collection, condition, params, cb) {
var self = this;
return self.connect(self.database + '/collections/' + collection + '/', 'PUT', condition, params, cb);
};
/*
MongoDB command
@collection {String}
@id {String or Number}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.findId = function(collection, id, cb) {
var self = this;
return self.connect(self.database + '/collections/' + collection + '/' + id + '/', 'GET', null, null, cb);
};
/*
MongoDB command
@collection {String}
@id {String or Number}
@document {Object}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.updateId = function(collection, id, document, cb) {
var self = this;
return self.connect(self.database + '/collections/' + collection + '/' + id + '/', 'PUT', document, null, cb);
};
/*
MongoDB command
@collection {String}
@id {String or Number}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.deleteId = function(collection, id, cb) {
var self = this;
return self.connect(self.database + '/collections/' + collection + '/' + id + '/', 'DELETE', null, null, cb);
};
/*
MongoDB command
@command {Object}
@cb {Function} :: function(error, object)
return {MongoDB}
*/
MongoDB.prototype.command = function(command, cb) {
var self = this;
return self.connect(self.database + '/runCommand/', 'POST', command, null, cb);
};
// ======================================================
// EXPORTS
// ======================================================
exports.timeout = 10000;
exports.MongoDB = exports.mongolab = exports.mongodb = MongoDB;
/*
MongoDB class
@connectionString {String} :: url address
*/
exports.init = function(connectionString, key) {
return new MongoDB(connectionString, key);
};