-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (77 loc) · 1.92 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
"use strict";
// module for sending messages to log collection in mongo
//
// Usage:
// var db = require('quai-mongo');
// var message = {foo: 'bar'}
//
// var insert = db('mongodb://localhost/quai', function(err){
// if (err) { console.error(err); return 1; };
// console.log('Connected.');
//
// insert(message, function(err){
// if (err) { console.error(err); return 1; };
//
// console.log('Saved. message: ', message);
// });
// });
// =>
// Connected.
// Saved. message: { foo: 'bar' }
// core module
var util = require('util');
// npm package
var MongoClient = require('mongodb').MongoClient;
// my modules
// var formatMessage = require('./formatMessage.js');
var dbCon = null;
module.exports = function(dbUrl, cb) {
MongoClient.connect(dbUrl, function(err, db) {
if(err) {
if (cb) {
cb(err);
return 1;
}
console.error("Can't connect to MongoDB", err);
return 1;
};
dbCon = db;
if (cb) {
cb(null);
return 1;
}
console.log('connected to mongoDB', dbUrl);
});
return function(message, cb) {
var clonedMessage = {};
Object.keys( message ).forEach(function ( k ) {
clonedMessage[k] = message[k];
});
if (!dbCon) {
var msg = "Can't insert message since there is no connection to MongoDB.";
if(cb) {
cb(msg);
return 1;
};
console.error(util.format('%s message: %j', msg, clonedMessage));
return 1;
};
dbCon.collection('log').insert(clonedMessage,
function(err, device) {
if (err) {
var msg = 'Error when Saving log in MongoDB. error:' + err;
if (cb) {
cb(msg);
return 1;
}
console.error(msg);
return 1;
}
if (cb) {
cb(null, clonedMessage);
return 1;
}
console.error(util.format('Saved to MongoDB. message: %j', clonedMessage));
});
};
};