roach-storm
Version:
Apache Kafka to Google Pub/Sub Gateway, API controlled
97 lines (96 loc) • 3.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Debug = require("debug");
const debug = Debug("roach:mongo");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Models = require("./models");
class MongoWrapper {
constructor(config, roachStorm) {
this.config = config;
this.models = {};
this.loadModels(roachStorm);
mongoose.set("bufferCommands", false);
mongoose.set("useCreateIndex", true);
mongoose.Promise = Promise;
}
loadModels(roachStorm) {
Object.keys(Models)
.map((key) => Models[key])
.forEach((modelConstructor) => {
if (modelConstructor.noModel) {
return;
}
const model = new modelConstructor(roachStorm, this);
model.registerModel(mongoose, Schema);
this.models[model.name] = model;
});
}
connectToMongoDB(attempts = 0) {
attempts++;
debug("Attempting to connect to MongoDB..", attempts);
return mongoose.connect(this.config.url, Object.assign({}, this.config.options, {
useNewUrlParser: true,
autoReconnect: true,
noDelay: true,
keepAlive: true,
reconnectTries: 30,
reconnectInterval: 1000,
poolSize: 10,
})).catch((error) => {
debug("Failed to connect to MongoDB: ", error.message);
return (new Promise((resolve) => { setTimeout(resolve, attempts * 1000); })).then(() => {
return this.connectToMongoDB(attempts);
});
});
}
async connect() {
const db = mongoose.connection;
db.on("error", (error) => {
debug("Error occured", error.message);
mongoose.disconnect();
});
db.on("connecting", () => {
debug("Connecting to MongoDB..");
});
db.on("connected", () => {
debug("Connected to MongoDB.");
});
db.on("reconnected", () => {
debug("MongoDB reconnected.");
});
db.on("disconnected", () => {
debug("MongoDB disconnected, reconnecting in 3 seconds..");
setTimeout(() => {
this.connectToMongoDB();
}, 3000);
});
return new Promise((resolve) => {
db.once("open", () => {
debug("Connection to MongoDB open.");
resolve(this);
});
this.connectToMongoDB();
});
}
isConnected() {
return mongoose.connection ? mongoose.connection.readyState === 1 : false;
}
async start() {
await this.connect();
return this.isConnected();
}
getTopicConfig() {
return this.models.topicconfig;
}
getSharedState() {
return this.models.state;
}
close() {
debug("Closing..");
if (mongoose.connection) {
mongoose.connection.close();
}
}
}
exports.default = MongoWrapper;