@adinet/indigodb
Version:
ORM for PostgreSQL and MongoDB with real-time support
136 lines (135 loc) • 5.86 kB
JavaScript
;
// src/orm.ts
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("pg");
const mongodb_1 = require("mongodb");
const ws_1 = __importStar(require("ws"));
const events_1 = require("events");
const postgresModel_1 = __importDefault(require("./models/postgresModel"));
const mongoModel_1 = __importDefault(require("./models/mongoModel"));
class ORM extends events_1.EventEmitter {
constructor() {
super();
this.models = {};
this.clients = [];
}
initialize(config) {
return __awaiter(this, void 0, void 0, function* () {
this.config = config;
if (config.databaseType === "postgresql") {
// Configuración para PostgreSQL
this.client = new pg_1.Client({
host: config.host,
port: config.port,
user: config.user,
password: config.password,
database: config.database,
});
yield this.client.connect();
yield this.setupPostgresListeners();
}
else if (config.databaseType === "mongodb") {
// Configuración para MongoDB
if (!config.connectionString) {
throw new Error("Se requiere connectionString para MongoDB");
}
this.mongoClient = new mongodb_1.MongoClient(config.connectionString);
yield this.mongoClient.connect();
this.mongoDb = this.mongoClient.db();
console.log("Conectado a MongoDB");
}
else {
throw new Error("Tipo de base de datos no soportado");
}
// Iniciar el servidor WebSocket internamente
this.startWebSocketServer(config.websocketPort || 8080);
});
}
startWebSocketServer(port) {
this.wss = new ws_1.Server({ port });
console.log(`Servidor WebSocket escuchando en el puerto ${port}`);
this.wss.on("connection", (ws) => {
this.clients.push(ws);
console.log("Cliente conectado al servidor WebSocket");
ws.on("close", () => {
this.clients = this.clients.filter((client) => client !== ws);
console.log("Cliente desconectado del servidor WebSocket");
});
});
}
broadcast(event, data) {
const message = JSON.stringify({ event, data });
this.clients.forEach((client) => {
if (client.readyState === ws_1.default.OPEN) {
client.send(message);
}
});
}
defineModel(name, schema) {
if (this.config.databaseType === "postgresql") {
return this.definePostgresModel(name, schema);
}
else if (this.config.databaseType === "mongodb") {
return this.defineMongoModel(name, schema);
}
else {
throw new Error("Tipo de base de datos no soportado");
}
}
definePostgresModel(name, schema) {
const model = new postgresModel_1.default(name, schema, this);
this.models[name] = model;
return model;
}
defineMongoModel(name, schema) {
const model = new mongoModel_1.default(name, schema, this);
this.models[name] = model;
return model;
}
setupPostgresListeners() {
return __awaiter(this, void 0, void 0, function* () {
yield this.client.query("LISTEN realtime_updates");
this.client.on("notification", (msg) => {
const payload = JSON.parse(msg.payload);
// console.log("Notification received from PostgreSQL:", msg.payload);
this.broadcast("databaseUpdate", payload);
});
});
}
}
exports.default = ORM;