@orxataguy/tyr 1.0.8 → 1.0.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orxataguy/tyr",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "tyr": "./bin/tyr.js"
@@ -49,6 +49,7 @@
49
49
  "find-config": "^1.0.0",
50
50
  "inquirer": "^13.2.1",
51
51
  "js-yaml": "^4.1.1",
52
+ "mongodb": "^7.2.0",
52
53
  "mssql": "^12.2.0",
53
54
  "tsx": "^4.21.0"
54
55
  },
@@ -0,0 +1,176 @@
1
+ import { MongoClient, Db, Document, Filter, UpdateFilter, InsertOneResult, InsertManyResult, UpdateResult, DeleteResult, WithId, OptionalUnlessRequiredId, FindOptions } from 'mongodb';
2
+
3
+ /**
4
+ * @class MongoManager
5
+ * @description Conector con MongoDB que gestiona el ciclo de vida de la conexión y expone un CRUD genérico.
6
+ */
7
+ export class MongoManager {
8
+ private client!: MongoClient;
9
+ private db!: Db;
10
+ private connected = false;
11
+
12
+ constructor() {}
13
+
14
+ private async init(): Promise<void> {
15
+ if (!this.connected) {
16
+ const uri = process.env.MONGO_URI || 'mongodb://localhost:27017';
17
+ const dbName = process.env.MONGO_DATABASE || '';
18
+
19
+ this.client = new MongoClient(uri);
20
+ await this.client.connect();
21
+ this.db = this.client.db(dbName);
22
+ this.connected = true;
23
+ }
24
+ }
25
+
26
+ private async close(): Promise<void> {
27
+ if (this.connected && this.client) {
28
+ await this.client.close();
29
+ this.connected = false;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * @method insertOne
35
+ * @description Inserta un documento en la colección indicada.
36
+ * @param {string} collection - Nombre de la colección.
37
+ * @param {Document} document - Documento a insertar.
38
+ * @returns {Promise<InsertOneResult>} Resultado de la inserción.
39
+ * @example
40
+ * const result = await mongo.insertOne('users', { name: 'Ana', age: 30 });
41
+ */
42
+ public async insertOne<T extends Document>(collection: string, document: OptionalUnlessRequiredId<T>): Promise<InsertOneResult<T>> {
43
+ await this.init();
44
+ const result = await this.db.collection<T>(collection).insertOne(document);
45
+ await this.close();
46
+ return result;
47
+ }
48
+
49
+ /**
50
+ * @method insertMany
51
+ * @description Inserta múltiples documentos en la colección indicada.
52
+ * @param {string} collection - Nombre de la colección.
53
+ * @param {Document[]} documents - Array de documentos a insertar.
54
+ * @returns {Promise<InsertManyResult>} Resultado de la inserción.
55
+ * @example
56
+ * const result = await mongo.insertMany('users', [{ name: 'Ana' }, { name: 'Luis' }]);
57
+ */
58
+ public async insertMany<T extends Document>(collection: string, documents: OptionalUnlessRequiredId<T>[]): Promise<InsertManyResult<T>> {
59
+ await this.init();
60
+ const result = await this.db.collection<T>(collection).insertMany(documents);
61
+ await this.close();
62
+ return result;
63
+ }
64
+
65
+ /**
66
+ * @method findOne
67
+ * @description Busca el primer documento que coincida con el filtro.
68
+ * @param {string} collection - Nombre de la colección.
69
+ * @param {Filter<Document>} filter - Filtro de búsqueda.
70
+ * @param {FindOptions} [options] - Opciones adicionales (proyección, etc.).
71
+ * @returns {Promise<WithId<T> | null>} El documento encontrado o null.
72
+ * @example
73
+ * const user = await mongo.findOne('users', { name: 'Ana' });
74
+ */
75
+ public async findOne<T extends Document>(collection: string, filter: Filter<T>, options?: FindOptions): Promise<WithId<T> | null> {
76
+ await this.init();
77
+ const result = await this.db.collection<T>(collection).findOne(filter, options);
78
+ await this.close();
79
+ return result;
80
+ }
81
+
82
+ /**
83
+ * @method find
84
+ * @description Busca todos los documentos que coincidan con el filtro.
85
+ * @param {string} collection - Nombre de la colección.
86
+ * @param {Filter<Document>} filter - Filtro de búsqueda. Usa {} para traer todos los documentos.
87
+ * @param {FindOptions} [options] - Opciones adicionales (proyección, límite, etc.).
88
+ * @returns {Promise<WithId<T>[]>} Array de documentos encontrados.
89
+ * @example
90
+ * const users = await mongo.find('users', { age: { $gte: 18 } });
91
+ */
92
+ public async find<T extends Document>(collection: string, filter: Filter<T>, options?: FindOptions): Promise<WithId<T>[]> {
93
+ await this.init();
94
+ const result = await this.db.collection<T>(collection).find(filter, options).toArray();
95
+ await this.close();
96
+ return result;
97
+ }
98
+
99
+ /**
100
+ * @method updateOne
101
+ * @description Actualiza el primer documento que coincida con el filtro.
102
+ * @param {string} collection - Nombre de la colección.
103
+ * @param {Filter<Document>} filter - Filtro para identificar el documento.
104
+ * @param {UpdateFilter<Document>} update - Operación de actualización (ej: { $set: { field: value } }).
105
+ * @returns {Promise<UpdateResult>} Resultado de la actualización.
106
+ * @example
107
+ * const result = await mongo.updateOne('users', { name: 'Ana' }, { $set: { age: 31 } });
108
+ */
109
+ public async updateOne<T extends Document>(collection: string, filter: Filter<T>, update: UpdateFilter<T>): Promise<UpdateResult<T>> {
110
+ await this.init();
111
+ const result = await this.db.collection<T>(collection).updateOne(filter, update);
112
+ await this.close();
113
+ return result;
114
+ }
115
+
116
+ /**
117
+ * @method updateMany
118
+ * @description Actualiza todos los documentos que coincidan con el filtro.
119
+ * @param {string} collection - Nombre de la colección.
120
+ * @param {Filter<Document>} filter - Filtro para identificar los documentos.
121
+ * @param {UpdateFilter<Document>} update - Operación de actualización.
122
+ * @returns {Promise<UpdateResult>} Resultado de la actualización.
123
+ * @example
124
+ * const result = await mongo.updateMany('users', { active: false }, { $set: { active: true } });
125
+ */
126
+ public async updateMany<T extends Document>(collection: string, filter: Filter<T>, update: UpdateFilter<T>): Promise<UpdateResult<T>> {
127
+ await this.init();
128
+ const result = await this.db.collection<T>(collection).updateMany(filter, update);
129
+ await this.close();
130
+ return result;
131
+ }
132
+
133
+ /**
134
+ * @method deleteOne
135
+ * @description Elimina el primer documento que coincida con el filtro.
136
+ * @param {string} collection - Nombre de la colección.
137
+ * @param {Filter<Document>} filter - Filtro para identificar el documento.
138
+ * @returns {Promise<DeleteResult>} Resultado de la eliminación.
139
+ * @example
140
+ * const result = await mongo.deleteOne('users', { name: 'Ana' });
141
+ */
142
+ public async deleteOne<T extends Document>(collection: string, filter: Filter<T>): Promise<DeleteResult> {
143
+ await this.init();
144
+ const result = await this.db.collection<T>(collection).deleteOne(filter);
145
+ await this.close();
146
+ return result;
147
+ }
148
+
149
+ /**
150
+ * @method deleteMany
151
+ * @description Elimina todos los documentos que coincidan con el filtro.
152
+ * @param {string} collection - Nombre de la colección.
153
+ * @param {Filter<Document>} filter - Filtro para identificar los documentos.
154
+ * @returns {Promise<DeleteResult>} Resultado de la eliminación.
155
+ * @example
156
+ * const result = await mongo.deleteMany('users', { active: false });
157
+ */
158
+ public async deleteMany<T extends Document>(collection: string, filter: Filter<T>): Promise<DeleteResult> {
159
+ await this.init();
160
+ const result = await this.db.collection<T>(collection).deleteMany(filter);
161
+ await this.close();
162
+ return result;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * @object MongoManagerTests
168
+ * @description Parámetros de pruebas para validar la funcionalidad de MongoManager.
169
+ */
170
+ export const MongoManagerTests = {
171
+ // insertOne: { collection: 'test', document: { name: 'test_doc', value: 1 } },
172
+ // findOne: { collection: 'test', filter: { name: 'test_doc' } },
173
+ // find: { collection: 'test', filter: {} },
174
+ // updateOne: { collection: 'test', filter: { name: 'test_doc' }, update: { $set: { value: 2 } } },
175
+ // deleteOne: { collection: 'test', filter: { name: 'test_doc' } },
176
+ };