zamza
Version:
Apache Kafka discovery, indexing, searches, storage, hooks and HTTP gateway
119 lines (118 loc) • 3.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Debug = require("debug");
const debug = Debug("zamza:mongo");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const balrok_1 = require("balrok");
const Models = require("./models");
class MongoWrapper {
constructor(config, zamza) {
this.config = config;
this.models = {};
this.loadModels(zamza);
this.balrok = new balrok_1.default({
cacheCollectionName: "zamza_heavy_lifting",
cacheTimeMs: 60 * 1000 * 10,
maxParallelProcesses: 4,
});
mongoose.set("bufferCommands", false);
mongoose.set("useCreateIndex", true);
mongoose.Promise = Promise;
}
loadModels(zamza) {
Object.keys(Models)
.map((key) => Models[key])
.forEach((modelConstructor) => {
if (modelConstructor.noModel) {
return;
}
const model = new modelConstructor(zamza, 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();
await this.balrok.init();
return this.isConnected();
}
getKeyIndex() {
return this.models.keyindex;
}
getTopicConfig() {
return this.models.topicconfig;
}
getTopicMetadata() {
return this.models.topicmetadata;
}
getLock() {
return this.models.lock;
}
getHook() {
return this.models.hook;
}
getReplay() {
return this.models.replay;
}
getSharedState() {
return this.models.state;
}
close() {
debug("Closing..");
if (mongoose.connection) {
mongoose.connection.close();
}
}
}
exports.default = MongoWrapper;