dbcube 1.1.53 → 1.1.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +0 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +2 -8
- package/dist/index.js +0 -18
- package/package.json +3 -3
- package/src/lib/Dbcube.ts +2 -28
package/dist/index.cjs
CHANGED
|
@@ -118,7 +118,6 @@ var Dbcube = class _Dbcube {
|
|
|
118
118
|
config;
|
|
119
119
|
databases;
|
|
120
120
|
initialized;
|
|
121
|
-
initPromise = null;
|
|
122
121
|
/**
|
|
123
122
|
* Creates a new Dbcube instance (Singleton pattern)
|
|
124
123
|
*
|
|
@@ -136,7 +135,6 @@ var Dbcube = class _Dbcube {
|
|
|
136
135
|
this.config = new import_core.Config();
|
|
137
136
|
this.databases = {};
|
|
138
137
|
this.initialized = false;
|
|
139
|
-
this.initPromise = null;
|
|
140
138
|
_Dbcube.instance = this;
|
|
141
139
|
}
|
|
142
140
|
/**
|
|
@@ -173,21 +171,6 @@ var Dbcube = class _Dbcube {
|
|
|
173
171
|
*/
|
|
174
172
|
async init(configCreate = {}) {
|
|
175
173
|
if (this.initialized) return;
|
|
176
|
-
if (this.initPromise) {
|
|
177
|
-
return this.initPromise;
|
|
178
|
-
}
|
|
179
|
-
this.initPromise = this._performInit(configCreate);
|
|
180
|
-
try {
|
|
181
|
-
await this.initPromise;
|
|
182
|
-
} finally {
|
|
183
|
-
this.initPromise = null;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Performs the actual initialization process
|
|
188
|
-
* @private
|
|
189
|
-
*/
|
|
190
|
-
async _performInit(configCreate = {}) {
|
|
191
174
|
await this.loadConfig();
|
|
192
175
|
let config;
|
|
193
176
|
try {
|
|
@@ -212,7 +195,6 @@ var Dbcube = class _Dbcube {
|
|
|
212
195
|
if (configCreate.databaseName) {
|
|
213
196
|
this.databases[configCreate.databaseName] = new import_query_builder.Database(configCreate.databaseName);
|
|
214
197
|
}
|
|
215
|
-
this.initialized = true;
|
|
216
198
|
}
|
|
217
199
|
/**
|
|
218
200
|
* Gets a database connection instance for query building
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/lib/Dbcube.ts","../src/lib/FileUtils.ts"],"sourcesContent":["import { Dbcube } from './lib/Dbcube';\r\nimport { Database, Table } from '@dbcube/query-builder';\r\n\r\n// Re-export the types directly from the definition\r\nexport { \r\n Dbcube,\r\n Database,\r\n Table\r\n};\r\n\r\n// Export types using interface definitions for better compatibility\r\nexport type DatabaseRecord = Record<string, any>;\r\nexport type WhereCallback = (query: Table) => void;","import { Config } from '@dbcube/core';\r\nimport { Database } from '@dbcube/query-builder';\r\nimport FileUtils from './FileUtils';\r\nimport path from 'path';\r\nimport { createRequire } from 'module';\r\n\r\n/**\r\n * DBCube ORM - Main class for database management\r\n * \r\n * A lightweight, flexible ORM that supports multiple database engines including \r\n * MySQL, PostgreSQL, SQLite, and MongoDB with a fluent query builder interface.\r\n * \r\n * @example\r\n * ```typescript\r\n * import { Dbcube } from 'dbcube';\r\n * \r\n * const dbcube = new Dbcube();\r\n * await dbcube.init();\r\n * \r\n * // Get a database connection\r\n * const db = dbcube.database('myDatabase');\r\n * \r\n * // Use query builder\r\n * const users = await db.table('users').select().where('active', true).get();\r\n * ```\r\n * \r\n * @class\r\n * @author Albert Araya\r\n * @license MIT\r\n */\r\nexport class Dbcube {\r\n private static instance: Dbcube;\r\n private configPath!: string;\r\n private config: any;\r\n private databases!: Record<string, any>;\r\n private initialized!: boolean;\r\n private initPromise: Promise<void> | null = null;\r\n\r\n /**\r\n * Creates a new Dbcube instance (Singleton pattern)\r\n * \r\n * @constructor\r\n * @example\r\n * ```typescript\r\n * const dbcube = new Dbcube();\r\n * ```\r\n */\r\n constructor() {\r\n if (Dbcube.instance) {\r\n return Dbcube.instance;\r\n }\r\n this.configPath = path.join(process.cwd(), 'dbcube.config.js');\r\n this.config = new Config();\r\n this.databases = {};\r\n this.initialized = false;\r\n this.initPromise = null;\r\n\r\n Dbcube.instance = this;\r\n }\r\n\r\n /**\r\n * Loads configuration from dbcube.config.js file\r\n * \r\n * @private\r\n * @returns {Promise<void>}\r\n * @throws {Error} If config file doesn't exist\r\n */\r\n async loadConfig() {\r\n const exists = await FileUtils.fileExists(this.configPath);\r\n exists ?? console.log('❌ Dont exists config file, please create a dbcube.config.js file');\r\n }\r\n\r\n /**\r\n * Initializes the Dbcube ORM with database configurations\r\n * \r\n * @param {Object} configCreate - Optional configuration for creating new database\r\n * @param {string} [configCreate.databaseName] - Name of the database to create\r\n * @param {string} [configCreate.motor] - Database engine (mysql, postgres, sqlite, mongodb)\r\n * @param {any} [configCreate.configAnswers] - Additional configuration answers\r\n * @returns {Promise<void>}\r\n * \r\n * @example\r\n * ```typescript\r\n * // Initialize with existing config\r\n * await dbcube.init();\r\n * \r\n * // Initialize with new database creation\r\n * await dbcube.init({\r\n * databaseName: 'myapp',\r\n * motor: 'mysql'\r\n * });\r\n * ```\r\n */\r\n async init(configCreate: { databaseName?: string; motor?: string; configAnswers?: any } = {}) {\r\n // Si ya está inicializado, retornar inmediatamente\r\n if (this.initialized) return;\r\n \r\n // Si ya hay una inicialización en progreso, esperar a que termine\r\n if (this.initPromise) {\r\n return this.initPromise;\r\n }\r\n\r\n // Crear la promesa de inicialización para evitar múltiples llamadas concurrentes\r\n this.initPromise = this._performInit(configCreate);\r\n \r\n try {\r\n await this.initPromise;\r\n } finally {\r\n // Limpiar la promesa una vez completada (exitosa o fallida)\r\n this.initPromise = null;\r\n }\r\n }\r\n\r\n /**\r\n * Performs the actual initialization process\r\n * @private\r\n */\r\n private async _performInit(configCreate: { databaseName?: string; motor?: string; configAnswers?: any } = {}) {\r\n await this.loadConfig();\r\n\r\n let config: any;\r\n try {\r\n // Use createRequire for better Next.js compatibility\r\n // Use __filename for CJS, process.cwd() for ESM\r\n const requireUrl = typeof __filename !== 'undefined' ? __filename : process.cwd();\r\n const require = createRequire(requireUrl);\r\n // Clear require cache to ensure fresh load\r\n delete require.cache[require.resolve(this.configPath)];\r\n const configModule = require(this.configPath);\r\n config = configModule.default || configModule;\r\n } catch (error: any) {\r\n console.log('❌ Config load error:', error);\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n console.log('❌ Config file not found, please create a dbcube.config.js file');\r\n return;\r\n }\r\n throw error;\r\n }\r\n\r\n config(this.config);\r\n const databases = Object.keys(this.config.getAllDatabases());\r\n\r\n for (const database of databases) {\r\n this.databases[database] = new Database(database);\r\n }\r\n if (configCreate.databaseName) {\r\n this.databases[configCreate.databaseName] = new Database(configCreate.databaseName);\r\n }\r\n\r\n this.initialized = true;\r\n }\r\n\r\n /**\r\n * Gets a database connection instance for query building\r\n * \r\n * @param {string} databaseName - Name of the database configuration\r\n * @returns {Database} Database instance with query builder capabilities\r\n * \r\n * @example\r\n * ```typescript\r\n * // Get database connection\r\n * const db = dbcube.database('myapp');\r\n * \r\n * // Use query builder methods\r\n * const users = await db.table('users')\r\n * .select(['id', 'name', 'email'])\r\n * .where('status', 'active')\r\n * .orderBy('created_at', 'desc')\r\n * .limit(10)\r\n * .get();\r\n * \r\n * // Insert data\r\n * await db.table('users').insert({\r\n * name: 'John Doe',\r\n * email: 'john@example.com'\r\n * });\r\n * \r\n * // Update data\r\n * await db.table('users')\r\n * .where('id', 1)\r\n * .update({ status: 'inactive' });\r\n * \r\n * // Delete data\r\n * await db.table('users').where('id', 1).delete();\r\n * ```\r\n */\r\n database(databaseName: string): Database {\r\n return this.databases[databaseName];\r\n }\r\n}\r\n\r\nexport default Dbcube;","import * as fs from 'fs';\r\nimport * as path from 'path';\r\n\r\nexport class FileUtils {\r\n /**\r\n * Verifica si un archivo existe (asincrónico).\r\n * @param filePath - Ruta del archivo.\r\n * @returns Promise que resuelve true si el archivo existe, false si no.\r\n */\r\n static async fileExists(filePath: string): Promise<boolean> {\r\n return new Promise<boolean>((resolve) => {\r\n fs.access(path.resolve(filePath), fs.constants.F_OK, (err) => {\r\n resolve(!err);\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Verifica si un archivo existe (sincrónico).\r\n * @param filePath - Ruta del archivo.\r\n * @returns True si el archivo existe, false si no.\r\n */\r\n static fileExistsSync(filePath: string): boolean {\r\n try {\r\n fs.accessSync(path.resolve(filePath), fs.constants.F_OK);\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Extrae el nombre de la base de datos de un string con formato @database().\r\n * @param input - String de entrada que contiene la referencia a la base de datos.\r\n * @returns El nombre de la base de datos o null si no se encuentra.\r\n */\r\n static extractDatabaseName(input: string): string | null {\r\n const match = input.match(/@database\\([\"']?([\\w-]+)[\"']?\\)/);\r\n return match ? match[1] : null;\r\n }\r\n\r\n /**\r\n * Lee recursivamente archivos que terminan en un sufijo dado y los ordena numéricamente.\r\n * @param dir - Directorio base (relativo o absoluto).\r\n * @param suffix - Sufijo de archivo (como 'table.cube').\r\n * @returns Rutas absolutas de los archivos encontrados y ordenados.\r\n */\r\n static getCubeFilesRecursively(dir: string, suffix: string): string[] {\r\n const baseDir = path.resolve(dir); // ✅ Asegura que sea absoluto\r\n const cubeFiles: string[] = [];\r\n\r\n function recurse(currentDir: string): void {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n recurse(fullPath);\r\n } else if (entry.isFile() && (entry.name.endsWith(suffix) || entry.name.includes(suffix))) {\r\n cubeFiles.push(fullPath); // Ya es absoluta\r\n }\r\n }\r\n }\r\n\r\n recurse(baseDir);\r\n\r\n // Ordenar por número si los archivos comienzan con un número\r\n cubeFiles.sort((a: string, b: string) => {\r\n const aNum = parseInt(path.basename(a));\r\n const bNum = parseInt(path.basename(b));\r\n return (isNaN(aNum) ? 0 : aNum) - (isNaN(bNum) ? 0 : bNum);\r\n });\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
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/Dbcube.ts","../src/lib/FileUtils.ts"],"sourcesContent":["import { Dbcube } from './lib/Dbcube';\r\nimport { Database, Table } from '@dbcube/query-builder';\r\n\r\n// Re-export the types directly from the definition\r\nexport { \r\n Dbcube,\r\n Database,\r\n Table\r\n};\r\n\r\n// Export types using interface definitions for better compatibility\r\nexport type DatabaseRecord = Record<string, any>;\r\nexport type WhereCallback = (query: Table) => void;","import { Config } from '@dbcube/core';\r\nimport { Database } from '@dbcube/query-builder';\r\nimport FileUtils from './FileUtils';\r\nimport path from 'path';\r\nimport { createRequire } from 'module';\r\n\r\n/**\r\n * DBCube ORM - Main class for database management\r\n * \r\n * A lightweight, flexible ORM that supports multiple database engines including \r\n * MySQL, PostgreSQL, SQLite, and MongoDB with a fluent query builder interface.\r\n * \r\n * @example\r\n * ```typescript\r\n * import { Dbcube } from 'dbcube';\r\n * \r\n * const dbcube = new Dbcube();\r\n * await dbcube.init();\r\n * \r\n * // Get a database connection\r\n * const db = dbcube.database('myDatabase');\r\n * \r\n * // Use query builder\r\n * const users = await db.table('users').select().where('active', true).get();\r\n * ```\r\n * \r\n * @class\r\n * @author Albert Araya\r\n * @license MIT\r\n */\r\nexport class Dbcube {\r\n private static instance: Dbcube;\r\n private configPath!: string;\r\n private config: any;\r\n private databases!: Record<string, any>;\r\n private initialized!: boolean;\r\n\r\n /**\r\n * Creates a new Dbcube instance (Singleton pattern)\r\n * \r\n * @constructor\r\n * @example\r\n * ```typescript\r\n * const dbcube = new Dbcube();\r\n * ```\r\n */\r\n constructor() {\r\n if (Dbcube.instance) {\r\n return Dbcube.instance;\r\n }\r\n this.configPath = path.join(process.cwd(), 'dbcube.config.js');\r\n this.config = new Config();\r\n this.databases = {};\r\n this.initialized = false;\r\n\r\n Dbcube.instance = this;\r\n }\r\n\r\n /**\r\n * Loads configuration from dbcube.config.js file\r\n * \r\n * @private\r\n * @returns {Promise<void>}\r\n * @throws {Error} If config file doesn't exist\r\n */\r\n async loadConfig() {\r\n const exists = await FileUtils.fileExists(this.configPath);\r\n exists ?? console.log('❌ Dont exists config file, please create a dbcube.config.js file');\r\n }\r\n\r\n /**\r\n * Initializes the Dbcube ORM with database configurations\r\n * \r\n * @param {Object} configCreate - Optional configuration for creating new database\r\n * @param {string} [configCreate.databaseName] - Name of the database to create\r\n * @param {string} [configCreate.motor] - Database engine (mysql, postgres, sqlite, mongodb)\r\n * @param {any} [configCreate.configAnswers] - Additional configuration answers\r\n * @returns {Promise<void>}\r\n * \r\n * @example\r\n * ```typescript\r\n * // Initialize with existing config\r\n * await dbcube.init();\r\n * \r\n * // Initialize with new database creation\r\n * await dbcube.init({\r\n * databaseName: 'myapp',\r\n * motor: 'mysql'\r\n * });\r\n * ```\r\n */\r\n async init(configCreate: { databaseName?: string; motor?: string; configAnswers?: any } = {}) {\r\n if (this.initialized) return;\r\n await this.loadConfig();\r\n\r\n let config: any;\r\n try {\r\n // Use createRequire for better Next.js compatibility\r\n // Use __filename for CJS, process.cwd() for ESM\r\n const requireUrl = typeof __filename !== 'undefined' ? __filename : process.cwd();\r\n const require = createRequire(requireUrl);\r\n // Clear require cache to ensure fresh load\r\n delete require.cache[require.resolve(this.configPath)];\r\n const configModule = require(this.configPath);\r\n config = configModule.default || configModule;\r\n } catch (error: any) {\r\n console.log('❌ Config load error:', error);\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n console.log('❌ Config file not found, please create a dbcube.config.js file');\r\n return;\r\n }\r\n throw error;\r\n }\r\n\r\n config(this.config);\r\n\r\n const databases = Object.keys(this.config.getAllDatabases());\r\n\r\n for (const database of databases) {\r\n this.databases[database] = new Database(database);\r\n }\r\n if (configCreate.databaseName) {\r\n this.databases[configCreate.databaseName] = new Database(configCreate.databaseName);\r\n }\r\n }\r\n\r\n /**\r\n * Gets a database connection instance for query building\r\n * \r\n * @param {string} databaseName - Name of the database configuration\r\n * @returns {Database} Database instance with query builder capabilities\r\n * \r\n * @example\r\n * ```typescript\r\n * // Get database connection\r\n * const db = dbcube.database('myapp');\r\n * \r\n * // Use query builder methods\r\n * const users = await db.table('users')\r\n * .select(['id', 'name', 'email'])\r\n * .where('status', 'active')\r\n * .orderBy('created_at', 'desc')\r\n * .limit(10)\r\n * .get();\r\n * \r\n * // Insert data\r\n * await db.table('users').insert({\r\n * name: 'John Doe',\r\n * email: 'john@example.com'\r\n * });\r\n * \r\n * // Update data\r\n * await db.table('users')\r\n * .where('id', 1)\r\n * .update({ status: 'inactive' });\r\n * \r\n * // Delete data\r\n * await db.table('users').where('id', 1).delete();\r\n * ```\r\n */\r\n database(databaseName: string) {\r\n return this.databases[databaseName];\r\n }\r\n}\r\n\r\nexport default Dbcube;","import * as fs from 'fs';\r\nimport * as path from 'path';\r\n\r\nexport class FileUtils {\r\n /**\r\n * Verifica si un archivo existe (asincrónico).\r\n * @param filePath - Ruta del archivo.\r\n * @returns Promise que resuelve true si el archivo existe, false si no.\r\n */\r\n static async fileExists(filePath: string): Promise<boolean> {\r\n return new Promise<boolean>((resolve) => {\r\n fs.access(path.resolve(filePath), fs.constants.F_OK, (err) => {\r\n resolve(!err);\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Verifica si un archivo existe (sincrónico).\r\n * @param filePath - Ruta del archivo.\r\n * @returns True si el archivo existe, false si no.\r\n */\r\n static fileExistsSync(filePath: string): boolean {\r\n try {\r\n fs.accessSync(path.resolve(filePath), fs.constants.F_OK);\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Extrae el nombre de la base de datos de un string con formato @database().\r\n * @param input - String de entrada que contiene la referencia a la base de datos.\r\n * @returns El nombre de la base de datos o null si no se encuentra.\r\n */\r\n static extractDatabaseName(input: string): string | null {\r\n const match = input.match(/@database\\([\"']?([\\w-]+)[\"']?\\)/);\r\n return match ? match[1] : null;\r\n }\r\n\r\n /**\r\n * Lee recursivamente archivos que terminan en un sufijo dado y los ordena numéricamente.\r\n * @param dir - Directorio base (relativo o absoluto).\r\n * @param suffix - Sufijo de archivo (como 'table.cube').\r\n * @returns Rutas absolutas de los archivos encontrados y ordenados.\r\n */\r\n static getCubeFilesRecursively(dir: string, suffix: string): string[] {\r\n const baseDir = path.resolve(dir); // ✅ Asegura que sea absoluto\r\n const cubeFiles: string[] = [];\r\n\r\n function recurse(currentDir: string): void {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n recurse(fullPath);\r\n } else if (entry.isFile() && (entry.name.endsWith(suffix) || entry.name.includes(suffix))) {\r\n cubeFiles.push(fullPath); // Ya es absoluta\r\n }\r\n }\r\n }\r\n\r\n recurse(baseDir);\r\n\r\n // Ordenar por número si los archivos comienzan con un número\r\n cubeFiles.sort((a: string, b: string) => {\r\n const aNum = parseInt(path.basename(a));\r\n const bNum = parseInt(path.basename(b));\r\n return (isNaN(aNum) ? 0 : aNum) - (isNaN(bNum) ? 0 : bNum);\r\n });\r\n\r\n return cubeFiles;\r\n }\r\n}\r\n\r\nexport default FileUtils;"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAuB;AACvB,2BAAyB;;;ACDzB,SAAoB;AACpB,WAAsB;AAEf,IAAM,YAAN,MAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrB,aAAa,WAAW,UAAoC;AAC1D,WAAO,IAAI,QAAiB,CAACA,aAAY;AACvC,MAAG,UAAY,aAAQ,QAAQ,GAAM,aAAU,MAAM,CAAC,QAAQ;AAC5D,QAAAA,SAAQ,CAAC,GAAG;AAAA,MACd,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,eAAe,UAA2B;AAC/C,QAAI;AACF,MAAG,cAAgB,aAAQ,QAAQ,GAAM,aAAU,IAAI;AACvD,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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoCA,SAAS,cAAsB;AAC3B,WAAO,KAAK,UAAU,YAAY;AAAA,EACtC;AACJ;;;ADlKA,IAAAC,wBAAgC;","names":["resolve","path","require","import_query_builder"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Table } from '@dbcube/query-builder';
|
|
2
2
|
export { Database, Table } from '@dbcube/query-builder';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -31,7 +31,6 @@ declare class Dbcube {
|
|
|
31
31
|
private config;
|
|
32
32
|
private databases;
|
|
33
33
|
private initialized;
|
|
34
|
-
private initPromise;
|
|
35
34
|
/**
|
|
36
35
|
* Creates a new Dbcube instance (Singleton pattern)
|
|
37
36
|
*
|
|
@@ -76,11 +75,6 @@ declare class Dbcube {
|
|
|
76
75
|
motor?: string;
|
|
77
76
|
configAnswers?: any;
|
|
78
77
|
}): Promise<void>;
|
|
79
|
-
/**
|
|
80
|
-
* Performs the actual initialization process
|
|
81
|
-
* @private
|
|
82
|
-
*/
|
|
83
|
-
private _performInit;
|
|
84
78
|
/**
|
|
85
79
|
* Gets a database connection instance for query building
|
|
86
80
|
*
|
|
@@ -115,7 +109,7 @@ declare class Dbcube {
|
|
|
115
109
|
* await db.table('users').where('id', 1).delete();
|
|
116
110
|
* ```
|
|
117
111
|
*/
|
|
118
|
-
database(databaseName: string):
|
|
112
|
+
database(databaseName: string): any;
|
|
119
113
|
}
|
|
120
114
|
|
|
121
115
|
type DatabaseRecord = Record<string, any>;
|
package/dist/index.js
CHANGED
|
@@ -80,7 +80,6 @@ var Dbcube = class _Dbcube {
|
|
|
80
80
|
config;
|
|
81
81
|
databases;
|
|
82
82
|
initialized;
|
|
83
|
-
initPromise = null;
|
|
84
83
|
/**
|
|
85
84
|
* Creates a new Dbcube instance (Singleton pattern)
|
|
86
85
|
*
|
|
@@ -98,7 +97,6 @@ var Dbcube = class _Dbcube {
|
|
|
98
97
|
this.config = new Config();
|
|
99
98
|
this.databases = {};
|
|
100
99
|
this.initialized = false;
|
|
101
|
-
this.initPromise = null;
|
|
102
100
|
_Dbcube.instance = this;
|
|
103
101
|
}
|
|
104
102
|
/**
|
|
@@ -135,21 +133,6 @@ var Dbcube = class _Dbcube {
|
|
|
135
133
|
*/
|
|
136
134
|
async init(configCreate = {}) {
|
|
137
135
|
if (this.initialized) return;
|
|
138
|
-
if (this.initPromise) {
|
|
139
|
-
return this.initPromise;
|
|
140
|
-
}
|
|
141
|
-
this.initPromise = this._performInit(configCreate);
|
|
142
|
-
try {
|
|
143
|
-
await this.initPromise;
|
|
144
|
-
} finally {
|
|
145
|
-
this.initPromise = null;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Performs the actual initialization process
|
|
150
|
-
* @private
|
|
151
|
-
*/
|
|
152
|
-
async _performInit(configCreate = {}) {
|
|
153
136
|
await this.loadConfig();
|
|
154
137
|
let config;
|
|
155
138
|
try {
|
|
@@ -174,7 +157,6 @@ var Dbcube = class _Dbcube {
|
|
|
174
157
|
if (configCreate.databaseName) {
|
|
175
158
|
this.databases[configCreate.databaseName] = new Database(configCreate.databaseName);
|
|
176
159
|
}
|
|
177
|
-
this.initialized = true;
|
|
178
160
|
}
|
|
179
161
|
/**
|
|
180
162
|
* Gets a database connection instance for query building
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dbcube",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.54",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"access": "public"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@dbcube/core": "^1.0.
|
|
58
|
-
"@dbcube/query-builder": "^1.0.
|
|
57
|
+
"@dbcube/core": "^1.0.62",
|
|
58
|
+
"@dbcube/query-builder": "^1.0.43"
|
|
59
59
|
},
|
|
60
60
|
"repository": {
|
|
61
61
|
"type": "git",
|
package/src/lib/Dbcube.ts
CHANGED
|
@@ -34,7 +34,6 @@ export class Dbcube {
|
|
|
34
34
|
private config: any;
|
|
35
35
|
private databases!: Record<string, any>;
|
|
36
36
|
private initialized!: boolean;
|
|
37
|
-
private initPromise: Promise<void> | null = null;
|
|
38
37
|
|
|
39
38
|
/**
|
|
40
39
|
* Creates a new Dbcube instance (Singleton pattern)
|
|
@@ -53,7 +52,6 @@ export class Dbcube {
|
|
|
53
52
|
this.config = new Config();
|
|
54
53
|
this.databases = {};
|
|
55
54
|
this.initialized = false;
|
|
56
|
-
this.initPromise = null;
|
|
57
55
|
|
|
58
56
|
Dbcube.instance = this;
|
|
59
57
|
}
|
|
@@ -92,30 +90,7 @@ export class Dbcube {
|
|
|
92
90
|
* ```
|
|
93
91
|
*/
|
|
94
92
|
async init(configCreate: { databaseName?: string; motor?: string; configAnswers?: any } = {}) {
|
|
95
|
-
// Si ya está inicializado, retornar inmediatamente
|
|
96
93
|
if (this.initialized) return;
|
|
97
|
-
|
|
98
|
-
// Si ya hay una inicialización en progreso, esperar a que termine
|
|
99
|
-
if (this.initPromise) {
|
|
100
|
-
return this.initPromise;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// Crear la promesa de inicialización para evitar múltiples llamadas concurrentes
|
|
104
|
-
this.initPromise = this._performInit(configCreate);
|
|
105
|
-
|
|
106
|
-
try {
|
|
107
|
-
await this.initPromise;
|
|
108
|
-
} finally {
|
|
109
|
-
// Limpiar la promesa una vez completada (exitosa o fallida)
|
|
110
|
-
this.initPromise = null;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Performs the actual initialization process
|
|
116
|
-
* @private
|
|
117
|
-
*/
|
|
118
|
-
private async _performInit(configCreate: { databaseName?: string; motor?: string; configAnswers?: any } = {}) {
|
|
119
94
|
await this.loadConfig();
|
|
120
95
|
|
|
121
96
|
let config: any;
|
|
@@ -138,6 +113,7 @@ export class Dbcube {
|
|
|
138
113
|
}
|
|
139
114
|
|
|
140
115
|
config(this.config);
|
|
116
|
+
|
|
141
117
|
const databases = Object.keys(this.config.getAllDatabases());
|
|
142
118
|
|
|
143
119
|
for (const database of databases) {
|
|
@@ -146,8 +122,6 @@ export class Dbcube {
|
|
|
146
122
|
if (configCreate.databaseName) {
|
|
147
123
|
this.databases[configCreate.databaseName] = new Database(configCreate.databaseName);
|
|
148
124
|
}
|
|
149
|
-
|
|
150
|
-
this.initialized = true;
|
|
151
125
|
}
|
|
152
126
|
|
|
153
127
|
/**
|
|
@@ -184,7 +158,7 @@ export class Dbcube {
|
|
|
184
158
|
* await db.table('users').where('id', 1).delete();
|
|
185
159
|
* ```
|
|
186
160
|
*/
|
|
187
|
-
database(databaseName: string)
|
|
161
|
+
database(databaseName: string) {
|
|
188
162
|
return this.databases[databaseName];
|
|
189
163
|
}
|
|
190
164
|
}
|