MqttDispatcher/dist/mongosave.js

54 lines
1.9 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");
class MongoSave extends CallChain.AAsyncBaseChainItem {
2017-08-23 17:54:50 +02:00
constructor(url) {
2017-08-23 15:52:37 +02:00
super('MongoSave');
this.url = url;
this.mongoClient = new MongoDB.MongoClient();
this.connectPending = false;
2017-08-23 15:52:37 +02:00
}
func(message, finished) {
if (!this.dbh) {
2017-08-23 17:54:50 +02:00
log.info("Not database connection yet");
if (!this.connectPending) {
this.connectPending = true;
this.mongoClient.connect(this.url)
2017-08-23 17:54:50 +02:00
.then((db) => {
log.info("Successfully opened MongoDB connect");
this.dbh = db;
2017-08-23 17:54:50 +02:00
})
.catch((err) => {
log.error(`Failure when opening MongoDB connect: ${err}`);
this.dbh = undefined;
2017-08-23 17:54:50 +02:00
});
}
else {
log.info("Connecting to database is pending");
}
}
if (this.dbh) {
2017-08-23 17:54:50 +02:00
log.info("Database handle is available");
let coll = this.dbh.collection("iot");
2017-08-23 17:54:50 +02:00
coll.insertOne(message)
.then((res) => {
log.info(`Successfully wrote one item in database: ${res.insertedId}`);
let nextValue = { id: res.insertedId, payload: message };
finished(nextValue);
2017-08-23 17:54:50 +02:00
})
.catch((err) => {
log.error(`Failure when trying to write one item in database: ${err}`);
log.error("Chain interrupted");
2017-08-23 17:54:50 +02:00
});
}
else {
log.error(`No database connection yet, drop message ${message}`);
log.error("Chain interrupted");
2017-08-23 17:54:50 +02:00
}
log.info(`Returning from ${this.label}`);
2017-08-23 15:52:37 +02:00
}
}
exports.MongoSave = MongoSave;
//# sourceMappingURL=mongosave.js.map