2020-06-09 01:26:48 +01:00
|
|
|
var MongoClient = require("mongodb").MongoClient
|
|
|
|
var Winston = require("winston")
|
2020-06-08 20:56:17 +01:00
|
|
|
|
2020-06-09 01:26:48 +01:00
|
|
|
class MongoDocumentStore {
|
2020-06-08 20:56:17 +01:00
|
|
|
|
2020-06-09 01:26:48 +01:00
|
|
|
constructor(options) {
|
|
|
|
this.connectionURL = `mongodb+srv://${options.username}:${options.password}@cluster0-vycgu.mongodb.net/${options.dbName}?retryWrites=true&w=majority`;
|
|
|
|
this.dbName = options.dbName;
|
|
|
|
this.collectionName = options.collectionName;
|
|
|
|
}
|
2020-06-08 20:56:17 +01:00
|
|
|
|
2020-06-09 01:26:48 +01:00
|
|
|
set(key, data, callback) {
|
2020-06-08 20:56:17 +01:00
|
|
|
var _this = this;
|
2020-06-09 01:26:48 +01:00
|
|
|
const client = new MongoClient(this.connectionURL, { useUnifiedTopology: true, useNewUrlParser: true });
|
|
|
|
client.connect(err => {
|
|
|
|
if (err) {
|
|
|
|
callback(false);
|
|
|
|
Winston.error("Error connecting to MongoDB database.", { error: err });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const db = client.db(_this.dbName);
|
|
|
|
const collection = db.collection(_this.collectionName);
|
|
|
|
|
|
|
|
collection.insertOne({key: key, data: data}, (err, result) => {
|
2020-06-08 20:56:17 +01:00
|
|
|
if (err) {
|
|
|
|
callback(false);
|
2020-06-09 01:26:48 +01:00
|
|
|
Winston.error("Error inserting data into MongoDB database.", { error: error });
|
|
|
|
return;
|
2020-06-08 20:56:17 +01:00
|
|
|
}
|
2020-06-09 01:26:48 +01:00
|
|
|
Winston.info("Inserted data into MongoDB database.");
|
|
|
|
callback(true);
|
2020-06-08 20:56:17 +01:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-06-09 01:26:48 +01:00
|
|
|
get(key, callback) {
|
|
|
|
var _this = this;
|
|
|
|
MongoClient.connect(this.connectionURL, { useUnifiedTopology: true }, function(err, client) {
|
|
|
|
if (err) {
|
|
|
|
callback(false);
|
|
|
|
Winston.error("Error connecting to MongoDB database.", { error: err });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const db = client.db(_this.dbName);
|
|
|
|
const collection = db.collection(_this.collectionName);
|
|
|
|
|
|
|
|
collection.findOne({key: key}, (err, result) => {
|
|
|
|
if (err || !result) {
|
|
|
|
callback(false);
|
|
|
|
if (err) {
|
|
|
|
Winston.error("Error getting data from MongoDB database.", { error: error });
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
Winston.info("Retrieved data from MongoDB database.");
|
|
|
|
callback(result.data);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2020-06-08 20:56:17 +01:00
|
|
|
|
2020-06-09 01:26:48 +01:00
|
|
|
module.exports = MongoDocumentStore;
|