connected to atlas

This commit is contained in:
Wolfgang Hottgenroth
2017-08-23 17:54:50 +02:00
parent eb247646a0
commit a0a922f851
6 changed files with 131 additions and 5 deletions

View File

@ -12,7 +12,9 @@ let dispatcher = new mqtt.MqttDispatcher("mqtts://broker.hottis.de:8883",
dispatcher.register('IoT/espThermometer2/#', 'toJson', EspThermToJson.espThermToJson)
let mongo : MongoSave.MongoSave = new MongoSave.MongoSave()
let atlasUrl = "mongodb://receiver:esp8266.@cluster0-shard-00-00-7qduq.mongodb.net:27017,cluster0-shard-00-01-7qduq.mongodb.net:27017,cluster0-shard-00-02-7qduq.mongodb.net:27017/hottis?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin"
let mongo : MongoSave.MongoSave = new MongoSave.MongoSave(atlasUrl)
dispatcher.register('IoT/espThermometer2/#', 'MongoSave', mongo);

View File

@ -1,12 +1,52 @@
import * as CallChain from './callchain'
import * as log from './log'
import * as MongoDB from 'mongodb'
export class MongoSave extends CallChain.ABaseChainItem {
constructor() {
private _url : string
private _mongoClient : MongoDB.MongoClient
private _dbh : MongoDB.Db | undefined
private _connectPending : boolean
constructor(url:string) {
super('MongoSave')
this._url = url
this._mongoClient = new MongoDB.MongoClient()
this._connectPending = false
}
protected func(message : any) : any {
if (! this._dbh) {
log.info("Not database connection yet")
if (! this._connectPending) {
this._connectPending = true
this._mongoClient.connect(this._url)
.then((db:MongoDB.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 : MongoDB.Collection = this._dbh.collection("iot")
coll.insertOne(message)
.then((res : MongoDB.InsertOneWriteOpResult) => {
log.info(`Successfully wrote one item in database: ${res.insertedId}`)
})
.catch((err : any) => {
log.error(`Failure when trying to write one item in database: ${err}`)
})
} else {
log.error(`No database connection yet, drop message ${message}`)
}
return "<<" + message + ">>"
}