dbcube 5.1.5 → 5.2.1

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/src/lib/Dbcube.ts DELETED
@@ -1,160 +0,0 @@
1
- import { Config } from '@dbcube/core';
2
- import { Database } from '@dbcube/query-builder';
3
- import FileUtils from './FileUtils';
4
- import path from 'path';
5
- import { createRequire } from 'module';
6
-
7
- /**
8
- * Dbcube ORM - Main class for database management
9
- *
10
- * A lightweight, flexible ORM that supports multiple database engines including
11
- * MySQL, PostgreSQL, SQLite, and MongoDB with a fluent query builder interface.
12
- *
13
- * @example
14
- * ```typescript
15
- * import { Dbcube } from 'dbcube';
16
- *
17
- * const dbcube = new Dbcube();
18
- * await dbcube.init();
19
- *
20
- * // Get a database connection
21
- * const db = dbcube.database('myDatabase');
22
- *
23
- * // Use query builder
24
- * const users = await db.table('users').select().where('active', true).get();
25
- * ```
26
- *
27
- * @class
28
- * @author Albert Araya
29
- * @license MIT
30
- */
31
- export class Dbcube {
32
- private static instance: Dbcube;
33
- private configPath!: string;
34
- private config: any;
35
- private databases!: Record<string, any>;
36
-
37
- /**
38
- * Creates a new Dbcube instance (Singleton pattern)
39
- *
40
- * @constructor
41
- * @example
42
- * ```typescript
43
- * const dbcube = new Dbcube();
44
- * ```
45
- */
46
- constructor() {
47
- if (Dbcube.instance) {
48
- return Dbcube.instance;
49
- }
50
- this.configPath = path.join(process.cwd(), 'dbcube.config.js');
51
- this.config = new Config();
52
- this.databases = {};
53
- Dbcube.instance = this;
54
- }
55
-
56
- /**
57
- * Loads configuration from dbcube.config.js file
58
- *
59
- * @private
60
- * @returns {Promise<void>}
61
- * @throws {Error} If config file doesn't exist
62
- */
63
- async loadConfig() {
64
- const exists = await FileUtils.fileExists(this.configPath);
65
- exists ?? console.log('❌ Dont exists config file, please create a dbcube.config.js file');
66
- }
67
-
68
- /**
69
- * Initializes the Dbcube ORM with database configurations
70
- *
71
- * @param {Object} configCreate - Optional configuration for creating new database
72
- * @param {string} [configCreate.databaseName] - Name of the database to create
73
- * @param {string} [configCreate.motor] - Database engine (mysql, postgres, sqlite, mongodb)
74
- * @param {any} [configCreate.configAnswers] - Additional configuration answers
75
- * @returns {Promise<void>}
76
- *
77
- * @example
78
- * ```typescript
79
- * // Initialize with existing config
80
- * await dbcube.init();
81
- *
82
- * // Initialize with new database creation
83
- * await dbcube.init({
84
- * databaseName: 'myapp',
85
- * motor: 'mysql'
86
- * });
87
- * ```
88
- */
89
- init(configCreate: { databaseName?: string; motor?: string; configAnswers?: any } = {}) {
90
- let config: any;
91
- try {
92
- // Use createRequire for better Next.js compatibility
93
- // Use __filename for CJS, process.cwd() for ESM
94
- const requireUrl = typeof __filename !== 'undefined' ? __filename : process.cwd();
95
- const require = createRequire(requireUrl);
96
- // Clear require cache to ensure fresh load
97
- delete require.cache[require.resolve(this.configPath)];
98
- const configModule = require(this.configPath);
99
- config = configModule.default || configModule;
100
- } catch (error: any) {
101
- console.log('❌ Config load error:', error);
102
- if (error.code === 'MODULE_NOT_FOUND') {
103
- console.log('❌ Config file not found, please create a dbcube.config.js file');
104
- return;
105
- }
106
- throw error;
107
- }
108
-
109
- config(this.config);
110
-
111
- const databases = Object.keys(this.config.getAllDatabases());
112
-
113
- for (const database of databases) {
114
- this.databases[database] = new Database(database);
115
- }
116
- if (configCreate.databaseName) {
117
- this.databases[configCreate.databaseName] = new Database(configCreate.databaseName);
118
- }
119
- }
120
-
121
- /**
122
- * Gets a database connection instance for query building
123
- *
124
- * @param {string} databaseName - Name of the database configuration
125
- * @returns {Database} Database instance with query builder capabilities
126
- *
127
- * @example
128
- * ```typescript
129
- * // Get database connection
130
- * const db = dbcube.database('myapp');
131
- *
132
- * // Use query builder methods
133
- * const users = await db.table('users')
134
- * .select(['id', 'name', 'email'])
135
- * .where('status', 'active')
136
- * .orderBy('created_at', 'desc')
137
- * .limit(10)
138
- * .get();
139
- *
140
- * // Insert data
141
- * await db.table('users').insert({
142
- * name: 'John Doe',
143
- * email: 'john@example.com'
144
- * });
145
- *
146
- * // Update data
147
- * await db.table('users')
148
- * .where('id', 1)
149
- * .update({ status: 'inactive' });
150
- *
151
- * // Delete data
152
- * await db.table('users').where('id', 1).delete();
153
- * ```
154
- */
155
- database(databaseName: string) {
156
- return this.databases[databaseName];
157
- }
158
- }
159
-
160
- export default Dbcube;
@@ -1,79 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
-
4
- export class FileUtils {
5
- /**
6
- * Verifica si un archivo existe (asincrónico).
7
- * @param filePath - Ruta del archivo.
8
- * @returns Promise que resuelve true si el archivo existe, false si no.
9
- */
10
- static async fileExists(filePath: string): Promise<boolean> {
11
- return new Promise<boolean>((resolve) => {
12
- fs.access(path.resolve(filePath), fs.constants.F_OK, (err) => {
13
- resolve(!err);
14
- });
15
- });
16
- }
17
-
18
- /**
19
- * Verifica si un archivo existe (sincrónico).
20
- * @param filePath - Ruta del archivo.
21
- * @returns True si el archivo existe, false si no.
22
- */
23
- static fileExistsSync(filePath: string): boolean {
24
- try {
25
- fs.accessSync(path.resolve(filePath), fs.constants.F_OK);
26
- return true;
27
- } catch {
28
- return false;
29
- }
30
- }
31
-
32
- /**
33
- * Extrae el nombre de la base de datos de un string con formato @database().
34
- * @param input - String de entrada que contiene la referencia a la base de datos.
35
- * @returns El nombre de la base de datos o null si no se encuentra.
36
- */
37
- static extractDatabaseName(input: string): string | null {
38
- const match = input.match(/@database\(["']?([\w-]+)["']?\)/);
39
- return match ? match[1] : null;
40
- }
41
-
42
- /**
43
- * Lee recursivamente archivos que terminan en un sufijo dado y los ordena numéricamente.
44
- * @param dir - Directorio base (relativo o absoluto).
45
- * @param suffix - Sufijo de archivo (como 'table.cube').
46
- * @returns Rutas absolutas de los archivos encontrados y ordenados.
47
- */
48
- static getCubeFilesRecursively(dir: string, suffix: string): string[] {
49
- const baseDir = path.resolve(dir); // ✅ Asegura que sea absoluto
50
- const cubeFiles: string[] = [];
51
-
52
- function recurse(currentDir: string): void {
53
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
54
-
55
- for (const entry of entries) {
56
- const fullPath = path.join(currentDir, entry.name);
57
-
58
- if (entry.isDirectory()) {
59
- recurse(fullPath);
60
- } else if (entry.isFile() && (entry.name.endsWith(suffix) || entry.name.includes(suffix))) {
61
- cubeFiles.push(fullPath); // Ya es absoluta
62
- }
63
- }
64
- }
65
-
66
- recurse(baseDir);
67
-
68
- // Ordenar por número si los archivos comienzan con un número
69
- cubeFiles.sort((a: string, b: string) => {
70
- const aNum = parseInt(path.basename(a));
71
- const bNum = parseInt(path.basename(b));
72
- return (isNaN(aNum) ? 0 : aNum) - (isNaN(bNum) ? 0 : bNum);
73
- });
74
-
75
- return cubeFiles;
76
- }
77
- }
78
-
79
- export default FileUtils;
package/tsconfig.json DELETED
@@ -1,18 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ESNext",
4
- "module": "ESNext",
5
- "declaration": true, // Generar archivos .d.ts
6
- "declarationDir": "./dist",
7
- "outDir": "./dist", // Directorio de salida
8
- "moduleResolution": "bundler",
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "strict": true,
12
- "allowSyntheticDefaultImports": true,
13
- "rootDir": ".",
14
- "types": ["node"]
15
- },
16
- "include": ["src/**/*", "checkEnv.js"], // Incluye los archivos TypeScript
17
- "exclude": ["node_modules", "dist"]
18
- }
package/tsup.config.ts DELETED
@@ -1,14 +0,0 @@
1
- import { defineConfig } from 'tsup';
2
-
3
- export default defineConfig({
4
- entry: ['src/index.ts'], // Punto de entrada
5
- format: ['cjs', 'esm'], // Genera CommonJS y ES Modules
6
- dts: false,
7
- clean: true, // Limpia el directorio de salida
8
- outDir: 'dist', // Directorio de salida
9
- splitting: false, // Desactiva la división de código
10
- sourcemap: true, // Genera sourcemaps
11
- outExtension: ({ format }) => ({ // Forzar extensiones personalizadas
12
- js: format === 'cjs' ? '.cjs' : '.js',
13
- }),
14
- });