@developers-joyride/shortify
Version:
High performance URL shortener library with multi-database support (MongoDB, SQLite, PostgreSQL, MySQL)
93 lines (92 loc) • 3.18 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose_1 = __importDefault(require("mongoose"));
const events_1 = require("events");
class DatabaseConnection extends events_1.EventEmitter {
constructor(options) {
super();
this.retryCount = 0;
this.isConnected = false;
this.mongoUri = options.mongoUri;
this.maxRetries = options.maxRetries || 5;
this.retryDelay = options.retryDelay || 5000;
// Configure mongoose for high performance
mongoose_1.default.set("strictQuery", true);
}
/**
* Connect to MongoDB with retry capability
*/
async connect() {
try {
if (this.isConnected) {
return true;
}
// Optimized connection options for high throughput
await mongoose_1.default.connect(this.mongoUri, {
serverSelectionTimeoutMS: 5000,
maxPoolSize: 100, // Increased connection pool for high throughput
});
this.isConnected = true;
this.retryCount = 0;
this.emit("connected");
// Handle connection events
mongoose_1.default.connection.on("error", (err) => {
console.error("MongoDB connection error:", err);
this.isConnected = false;
this.emit("error", err);
this.retryConnection();
});
mongoose_1.default.connection.on("disconnected", () => {
this.isConnected = false;
this.emit("disconnected");
this.retryConnection();
});
return true;
}
catch (error) {
console.error("Failed to connect to MongoDB:", error);
this.emit("error", error);
return this.retryConnection();
}
}
/**
* Retry connection with exponential backoff
*/
retryConnection() {
if (this.retryCount < this.maxRetries) {
this.retryCount++;
// Exponential backoff
const delay = this.retryDelay * Math.pow(2, this.retryCount - 1);
console.log(`Retrying connection in ${delay}ms (attempt ${this.retryCount}/${this.maxRetries})`);
setTimeout(() => {
this.connect();
}, delay);
return true;
}
else {
this.emit("maxRetriesReached");
return false;
}
}
/**
* Disconnect from MongoDB
*/
async disconnect() {
if (mongoose_1.default.connection.readyState !== 0) {
await mongoose_1.default.disconnect();
this.isConnected = false;
this.emit("disconnected");
}
}
/**
* Get connection status
*/
getStatus() {
const states = ["disconnected", "connected", "connecting", "disconnecting"];
return states[mongoose_1.default.connection.readyState];
}
}
exports.default = DatabaseConnection;