MqttDispatcher/dist/mongosave.js

50 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-08-23 15:52:37 +02:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const CallChain = require("./callchain");
2017-08-23 17:54:50 +02:00
const log = require("./log");
const MongoDB = require("mongodb");
2017-08-23 15:52:37 +02:00
class MongoSave extends CallChain.ABaseChainItem {
2017-08-23 17:54:50 +02:00
constructor(url) {
2017-08-23 15:52:37 +02:00
super('MongoSave');
2017-08-23 17:54:50 +02:00
this._url = url;
this._mongoClient = new MongoDB.MongoClient();
this._connectPending = false;
2017-08-23 15:52:37 +02:00
}
func(message) {
2017-08-23 17:54:50 +02:00
if (!this._dbh) {
log.info("Not database connection yet");
if (!this._connectPending) {
this._connectPending = true;
this._mongoClient.connect(this._url)
.then((db) => {
log.info("Successfully opened MongoDB connect");
this._dbh = db;
})
.catch((err) => {
log.error(`Failure when opening MongoDB connect: ${err}`);
this._dbh = undefined;
});
}
else {
log.info("Connecting to database is pending");
}
}
if (this._dbh) {
log.info("Database handle is available");
let coll = this._dbh.collection("iot");
coll.insertOne(message)
.then((res) => {
log.info(`Successfully wrote one item in database: ${res.insertedId}`);
})
.catch((err) => {
log.error(`Failure when trying to write one item in database: ${err}`);
});
}
else {
log.error(`No database connection yet, drop message ${message}`);
}
2017-08-23 15:52:37 +02:00
return "<<" + message + ">>";
}
}
exports.MongoSave = MongoSave;
//# sourceMappingURL=mongosave.js.map