zormz 1.0.0

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/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # ZORM
2
+ Un ORM simple pero poderoso para el uso de cualquier usuario , no te enredes con cosas como definir las tablas
package/dist/index.cjs ADDED
@@ -0,0 +1,591 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
33
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
34
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
36
+
37
+ // index.ts
38
+ var index_exports = {};
39
+ __export(index_exports, {
40
+ AND: () => AND,
41
+ BDconnection: () => BDconnection,
42
+ DB: () => DB,
43
+ DeleteR: () => DeleteR,
44
+ ILIKE: () => ILIKE,
45
+ NOTNULL: () => NOTNULL,
46
+ NULL: () => NULL,
47
+ OR: () => OR,
48
+ ORQ: () => ORQ,
49
+ QueryBuilder: () => QueryBuilder,
50
+ Select: () => Select,
51
+ Update: () => Update,
52
+ eq: () => eq,
53
+ getConexion: () => getConexion,
54
+ getRed: () => getRed,
55
+ mayor: () => mayor,
56
+ menor: () => menor,
57
+ now: () => now
58
+ });
59
+ module.exports = __toCommonJS(index_exports);
60
+
61
+ // conection/db.ts
62
+ var conexion1;
63
+ var BDconnection = class {
64
+ constructor(bd, datos) {
65
+ this.tipo = "pg";
66
+ this.tipo = bd;
67
+ this.connection = datos;
68
+ }
69
+ async connecionMyql() {
70
+ try {
71
+ const mysql = await import("mysql2/promise");
72
+ if ("connectionString" in this.connection)
73
+ throw new Error("La conexion mysql no tiene una conexion de red");
74
+ const pool = mysql.createPool({
75
+ host: this.connection.host,
76
+ port: this.connection.port,
77
+ database: this.connection.database,
78
+ user: this.connection.user,
79
+ password: this.connection.password
80
+ });
81
+ return pool;
82
+ } catch (error) {
83
+ throw new Error("Mysql no esta instalado . para instalarlo corre : npm install mysql2 ");
84
+ }
85
+ }
86
+ async connectionPG() {
87
+ try {
88
+ const { Pool } = await import("pg");
89
+ if ("connectionString" in this.connection) {
90
+ console.log("conexion en linea");
91
+ return new Pool({
92
+ connectionString: this.connection.connectionString,
93
+ ssl: {
94
+ rejectUnauthorized: false
95
+ }
96
+ });
97
+ }
98
+ return new Pool({
99
+ host: this.connection.host,
100
+ port: this.connection.port,
101
+ database: this.connection.database,
102
+ user: this.connection.user,
103
+ password: this.connection.password
104
+ });
105
+ } catch (error) {
106
+ console.error(
107
+ "PostgreSQL no esta instalado. para instalarlo corre : npm install pg"
108
+ );
109
+ }
110
+ }
111
+ async executeConsulta({
112
+ query,
113
+ valores = void 0,
114
+ mensaje
115
+ }) {
116
+ try {
117
+ if (this.tipo === "mysql") {
118
+ const pool = await this.connecionMyql();
119
+ const [rows] = await pool.query(query, [valores]);
120
+ return rows;
121
+ } else if (this.tipo === "pg") {
122
+ let query2 = query;
123
+ if (valores) {
124
+ let iterador = 1;
125
+ query2 = "";
126
+ for (let i = 0; i < query.length; i++) {
127
+ if (query[i] == "?") {
128
+ query2 += `$${iterador}`;
129
+ iterador++;
130
+ } else {
131
+ query2 += query[i];
132
+ }
133
+ }
134
+ }
135
+ const pool2 = await this.connectionPG();
136
+ const respuesta = await pool2.query(query2, valores);
137
+ if (!respuesta) {
138
+ throw new Error(` Este usuario no esta registrado `);
139
+ }
140
+ if ("rows" in respuesta) {
141
+ if (respuesta.rows[0].id) {
142
+ return { insertId: respuesta.rows[0].id };
143
+ }
144
+ return respuesta.rows;
145
+ }
146
+ }
147
+ } catch (error) {
148
+ console.log(error);
149
+ if (typeof error === "object" && error !== null && "code" in error) {
150
+ if (error.code === "ETIMEDOUT") {
151
+ throw new Error(`Su red esta limitando el acceso`);
152
+ }
153
+ throw new Error(`${mensaje} : ${error} query ${query}`);
154
+ }
155
+ }
156
+ }
157
+ };
158
+ function getConexion(bd, datos) {
159
+ conexion1 = new BDconnection(bd, datos);
160
+ }
161
+ function getRed() {
162
+ return conexion1;
163
+ }
164
+
165
+ // conection/middleware/delete.ts
166
+ var _condicion, _tabla;
167
+ var DeleteR = class {
168
+ /**
169
+ *
170
+ * @param {string} tabla -- tabla a eliminar
171
+ * @example
172
+ * delete from tabla
173
+ */
174
+ constructor(conexion, tabla) {
175
+ __privateAdd(this, _condicion);
176
+ __privateAdd(this, _tabla);
177
+ __privateSet(this, _tabla, tabla);
178
+ __privateSet(this, _condicion, "");
179
+ this.conexion = conexion;
180
+ }
181
+ /**
182
+ *
183
+ * @param {string} condicion -- condicional de tabla
184
+ * @example
185
+ * DB.Delete(tabla).WHERE(eq(valor,valor))
186
+ * DB.Delete(tabla).WHERE(AND(eq(valor,valor), eq(valor2,valor2)))
187
+ */
188
+ where(condicion) {
189
+ if (!condicion || typeof condicion !== "string") {
190
+ throw new Error("La tabla es un campo obligatorio");
191
+ }
192
+ __privateSet(this, _condicion, ` where ${condicion}`);
193
+ return this;
194
+ }
195
+ async execute() {
196
+ const query = `DELETE FROM ${__privateGet(this, _tabla)} ${__privateGet(this, _condicion)}`;
197
+ const respuesta = await this.conexion.executeConsulta({
198
+ query,
199
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
200
+ });
201
+ return respuesta.affectedRows;
202
+ }
203
+ };
204
+ _condicion = new WeakMap();
205
+ _tabla = new WeakMap();
206
+
207
+ // conection/middleware/insertar.ts
208
+ var QueryBuilder = class {
209
+ /**
210
+ * @throws {Error} Si la consulta es vacía.
211
+ */
212
+ /**
213
+ * @param {string[]} parametros - campo obligatorio
214
+ * @param {string} tabla - nombre de la ta tabla - campo obligatorio
215
+ * @param {string[]} values - campo obligatorio
216
+ */
217
+ constructor(conexion, tabla, parametros) {
218
+ if (!parametros || !Array.isArray(parametros)) {
219
+ throw new Error(`campos obligatorios`);
220
+ }
221
+ if (!tabla || typeof tabla !== "string") {
222
+ throw new Error("Nombre tabla obligatorio");
223
+ }
224
+ this.tabla = tabla;
225
+ this.parametros = parametros;
226
+ this.valores = [];
227
+ this.valorRetorno = null;
228
+ this.conexion = conexion;
229
+ }
230
+ /**
231
+ *
232
+ * @param {arrayData | arrayDatas} values
233
+ * @example
234
+ * //para un salo dato
235
+ * ['dato1','dato2']
236
+ * //para varios datos
237
+ * [['dato1','dato1/2'],['dato2','dato2/2']]
238
+ *
239
+ * @returns
240
+ */
241
+ Values(values) {
242
+ if (!values || !Array.isArray(values)) {
243
+ throw new Error("los valores tienen que ser tipo array");
244
+ }
245
+ this.valores = values;
246
+ return this;
247
+ }
248
+ async execute() {
249
+ this.valorRetorno = 1;
250
+ let query1 = `INSERT INTO ${this.tabla} `;
251
+ let param = "";
252
+ let arrayArrays = false;
253
+ let paramespaces = "";
254
+ if (typeof this.parametros !== "string") {
255
+ if (Array.isArray(this.valores)) arrayArrays = true;
256
+ this.parametros.forEach((valor, index) => {
257
+ param += valor;
258
+ paramespaces += ` ? `;
259
+ if (index < this.parametros.length - 1) {
260
+ param += ", ";
261
+ paramespaces += ", ";
262
+ }
263
+ });
264
+ }
265
+ let query = `${query1} (${param}) VALUES `;
266
+ if (arrayArrays) {
267
+ query += ` ? `;
268
+ } else {
269
+ query += `(${paramespaces})`;
270
+ }
271
+ const respuesta = await this.conexion.executeConsulta({
272
+ query,
273
+ valores: this.valores,
274
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
275
+ });
276
+ return respuesta.insertId;
277
+ }
278
+ };
279
+
280
+ // conection/middleware/select.ts
281
+ var Select = class {
282
+ /**
283
+ * @param {string[]} parametros - campo obligatorio
284
+ * @param {string} tabla - nombre de la ta tabla - campo obligatorio
285
+ * @param {string[]} values - campo obligatorio
286
+ * @param {string} condition - tabla1.id = tabla2.idtabla1 - id='2' - id='2' AND id='3'
287
+ */
288
+ constructor(conexion, parametros = "*") {
289
+ this.conexion = conexion;
290
+ this.valores = !Array.isArray(parametros) ? false : true;
291
+ this.parametros = parametros;
292
+ this.tabla = void 0;
293
+ this.innerJoin = "";
294
+ this.leftjoins = "";
295
+ this.rigthjoins = "";
296
+ this.limit = "";
297
+ this.condicion = "";
298
+ this.orderBy = "";
299
+ }
300
+ /**
301
+ * @param {string} tabla - nombre de la ta tabla - campo obligatorio
302
+ */
303
+ from(tabla) {
304
+ if (!tabla || typeof tabla !== "string") {
305
+ throw new Error("La tabla es un campo obligatorio");
306
+ }
307
+ this.tabla = tabla;
308
+ return this;
309
+ }
310
+ innerJOIN(tabla, condition) {
311
+ if (!tabla || typeof tabla !== "string") {
312
+ throw new Error("La tabla es un campo obligatorio");
313
+ }
314
+ this.innerJoin += ` INNER JOIN ${tabla} ON ${condition}`;
315
+ return this;
316
+ }
317
+ leftJoin(tabla, condition) {
318
+ if (!tabla || typeof tabla !== "string") {
319
+ throw new Error("La tabla es un campo obligatorio");
320
+ }
321
+ this.leftjoins += ` LEFT JOIN ${tabla} ON ${condition}`;
322
+ return this;
323
+ }
324
+ rigthJoin(tabla, condition) {
325
+ if (!tabla || typeof tabla !== "string") {
326
+ throw new Error("La tabla es un campo obligatorio");
327
+ }
328
+ this.rigthjoins += ` RIGHT JOIN ${tabla} ON ${condition}`;
329
+ return this;
330
+ }
331
+ /**
332
+ * @param {string} condition - tabla1.id = tabla2.idtabla1 - id='2' - id='2' AND id='3'
333
+ */
334
+ where(condition = void 0) {
335
+ if (condition === void 0 || !condition) {
336
+ this.condicion = "";
337
+ } else {
338
+ if (this.condicion.length < 2) {
339
+ this.condicion += `WHERE `;
340
+ }
341
+ this.condicion += ` ${condition}`;
342
+ }
343
+ return this;
344
+ }
345
+ /**
346
+ * @typedef { "ASC" | "DESC" } tipos
347
+ */
348
+ /**
349
+ *
350
+ * @param {{
351
+ * [clave:string]:tipos
352
+ * }} objeto --Filtrado
353
+ * @example
354
+ * select().orderBy({nombre:'DESC',id:'ASC'});
355
+ */
356
+ OrderBy(objeto) {
357
+ if (typeof objeto !== "object")
358
+ throw new Error("Solo se permite objetos , error de OrderBy");
359
+ if (Object.keys(objeto).length === 0)
360
+ throw new Error("No se permite los campos vacios");
361
+ this.orderBy = " ORDER BY ";
362
+ for (const [clave, valor] of Object.entries(objeto)) {
363
+ if (valor !== "ASC" && valor !== "DESC")
364
+ throw new Error("ASC o DESC requerido para la consulta");
365
+ this.orderBy += ` ${clave} ${valor},`;
366
+ }
367
+ this.orderBy = this.orderBy.slice(0, -1);
368
+ return this;
369
+ }
370
+ /**
371
+ *
372
+ * @param {Number} cantidad
373
+ */
374
+ LIMIT(cantidad = 1) {
375
+ if (typeof cantidad != "number") {
376
+ throw new Error("Cantidad tiene que ser un numero");
377
+ }
378
+ this.limit = `LIMIT ${cantidad}`;
379
+ return this;
380
+ }
381
+ /**
382
+ *
383
+ * @param {String} texto
384
+ */
385
+ /**
386
+ * @returns {Promise<Array<Object>>}
387
+ */
388
+ async execute() {
389
+ let selectFields = "*";
390
+ if (this.valores) {
391
+ if (typeof this.parametros !== "undefined" && typeof this.parametros !== "string") {
392
+ selectFields = this.parametros.join(",");
393
+ }
394
+ }
395
+ const query = `SELECT ${selectFields} from ${this.tabla} ${this.innerJoin} ${this.leftjoins} ${this.rigthjoins} ${this.condicion} ${this.orderBy} ${this.limit};`;
396
+ const respuesta = await this.conexion.executeConsulta({
397
+ query,
398
+ mensaje: "Ocurrio un error realizar un select"
399
+ });
400
+ return respuesta;
401
+ }
402
+ };
403
+
404
+ // conection/middleware/condicionals.ts
405
+ var AND = (...valor1) => {
406
+ const separacion = valor1.join(" and ");
407
+ return `(${separacion})`;
408
+ };
409
+ var OR = (...valor1) => {
410
+ const separadosComas = valor1.join(" or ");
411
+ return `(${separadosComas})`;
412
+ };
413
+ var ORQ = (condicion1, ...condicionals) => {
414
+ const data2 = condicionals.map((dato) => {
415
+ if (typeof dato == "number" || typeof dato == "boolean") return ` '${condicion1}' = ${dato}`;
416
+ return ` '${condicion1}' = '${dato}' `;
417
+ });
418
+ const separador = data2.join(" or ");
419
+ return separador;
420
+ };
421
+ var ILIKE = (valor1, valor2) => {
422
+ return `${valor1} ILIKE '%${valor2}%'`;
423
+ };
424
+ var now = (variable, diasTrancurridos, minor = true) => {
425
+ if (typeof variable !== "string") {
426
+ throw new Error("Variable no valida");
427
+ }
428
+ if (typeof diasTrancurridos !== "number") {
429
+ throw new Error("dias Transcurridos no valido");
430
+ }
431
+ if (minor) {
432
+ return `( ${variable} < NOW() - INTERVAL '${diasTrancurridos} days')`;
433
+ }
434
+ return `( ${variable} > NOW() - INTERVAL '${diasTrancurridos} days')`;
435
+ };
436
+ var NULL = (variable) => {
437
+ return `${variable} IS NULL`;
438
+ };
439
+ var NOTNULL = (variable) => {
440
+ return `${variable} IS NOT NULL`;
441
+ };
442
+ var eq = (valor1, valor2, literal = true) => {
443
+ if (typeof valor1 === "string") valor1 = valor1.trim();
444
+ if (typeof valor2 === "string") valor2 = valor2.trim();
445
+ if (!literal) {
446
+ return `${valor1} = ${valor2}`;
447
+ }
448
+ return `${valor1} = '${valor2}'`;
449
+ };
450
+ var mayor = (valor, valor2) => {
451
+ return ` ${valor} > ${valor2} `;
452
+ };
453
+ var menor = (valor, valor2) => {
454
+ return ` ${valor} < ${valor2} `;
455
+ };
456
+
457
+ // conection/middleware/update.ts
458
+ var Update = class {
459
+ /**
460
+ * @param {string} nombreTabla - nombre de la tabla a actualizar
461
+ */
462
+ constructor(conexion, nombreTabla) {
463
+ this.nombreTabla = "";
464
+ this.valores = "";
465
+ this.condicion = "";
466
+ if (typeof nombreTabla !== "string") {
467
+ throw new Error("el valor ingresado requiere un string");
468
+ }
469
+ if (nombreTabla === void 0 || !nombreTabla) {
470
+ throw new Error("El nombre de la tabla es requerido");
471
+ }
472
+ this.nombreTabla = nombreTabla;
473
+ this.conexion = conexion;
474
+ }
475
+ /**
476
+ * @param {Valores} valores - valores a actualizar
477
+ * @example
478
+ * .set({'campo1':'valor1', 'campo2':'valor2'})
479
+ */
480
+ set(valores) {
481
+ if (typeof valores !== "object") {
482
+ throw new Error("es requerido un objeto");
483
+ }
484
+ let valor = "";
485
+ for (const key in valores) {
486
+ if (valores.hasOwnProperty(key)) {
487
+ const value = valores[key];
488
+ if (value === void 0) continue;
489
+ valor += eq(key, value);
490
+ valor += ",";
491
+ }
492
+ }
493
+ valor = valor.slice(0, -1);
494
+ this.valores = valor;
495
+ return this;
496
+ }
497
+ /**
498
+ * @param {string} condicion - valor condicional
499
+ * @example
500
+ * //para completar una condicional puedes usar
501
+ * where(eq())
502
+ * where(AND())
503
+ * where(OR())
504
+ * where(ORQ())
505
+ */
506
+ where(condicion) {
507
+ if (condicion === void 0 || !condicion) {
508
+ this.condicion = "";
509
+ } else {
510
+ if (this.condicion.length < 2) {
511
+ this.condicion += `WHERE `;
512
+ }
513
+ this.condicion += `${condicion}`;
514
+ }
515
+ return this;
516
+ }
517
+ async execute() {
518
+ const query = `UPDATE ${this.nombreTabla} SET ${this.valores} ${this.condicion};`;
519
+ const respuesta = await this.conexion.executeConsulta({
520
+ query,
521
+ mensaje: "Error Update"
522
+ });
523
+ if (this.conexion.tipo === "mysql") {
524
+ return respuesta;
525
+ } else {
526
+ return {
527
+ resultado: respuesta.rows.info,
528
+ filasAfectadas: respuesta.rows.affectedRows
529
+ };
530
+ }
531
+ }
532
+ };
533
+
534
+ // conection/conexion.ts
535
+ var DB = class {
536
+ /**
537
+ * @param {string} tabla - campo obligatorio
538
+ * @param {string[]} parametros - campo obligatorio
539
+ * @example
540
+ * DB.Insert('tabla',['campo1','campo2'])
541
+ */
542
+ static Insert(tabla, parametros) {
543
+ const conex = getRed();
544
+ return new QueryBuilder(conex, tabla, parametros);
545
+ }
546
+ /**
547
+ * @param {string[]} parametros - campo opcional
548
+ */
549
+ static select(parametros) {
550
+ const conex = getRed();
551
+ return new Select(conex, parametros);
552
+ }
553
+ /**
554
+ * @param {string} nombreTabla - nombre de la tabla a actualizar
555
+ */
556
+ static update(nombreTabla) {
557
+ const conex = getRed();
558
+ return new Update(conex, nombreTabla);
559
+ }
560
+ /**
561
+ *
562
+ * @param {string} nombreTabla -- tabla a eliminar
563
+ * @example
564
+ * delete from tabla
565
+ */
566
+ static Delete(nombreTabla) {
567
+ const conex = getRed();
568
+ return new DeleteR(conex, nombreTabla);
569
+ }
570
+ };
571
+ // Annotate the CommonJS export names for ESM import in node:
572
+ 0 && (module.exports = {
573
+ AND,
574
+ BDconnection,
575
+ DB,
576
+ DeleteR,
577
+ ILIKE,
578
+ NOTNULL,
579
+ NULL,
580
+ OR,
581
+ ORQ,
582
+ QueryBuilder,
583
+ Select,
584
+ Update,
585
+ eq,
586
+ getConexion,
587
+ getRed,
588
+ mayor,
589
+ menor,
590
+ now
591
+ });