nx-mongo 3.3.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/src/test.ts ADDED
@@ -0,0 +1,209 @@
1
+ import { SimpleMongoHelper } from './simpleMongoHelper';
2
+
3
+ async function testMongoHelper() {
4
+ // Try IPv4 first, fallback to localhost
5
+ const connectionString = 'mongodb://127.0.0.1:27017/test-db';
6
+ const helper = new SimpleMongoHelper(connectionString);
7
+
8
+ try {
9
+ console.log('šŸ”Œ Initializing MongoDB connection...');
10
+ await helper.initialize();
11
+ console.log('āœ… Connected to MongoDB successfully!\n');
12
+
13
+ // Test 1: Insert single document
14
+ console.log('šŸ“ Test 1: Inserting single document into "users" collection...');
15
+ const insertResult1 = await helper.insert('users', {
16
+ name: 'John Doe',
17
+ email: 'john@example.com',
18
+ age: 30,
19
+ role: 'admin'
20
+ });
21
+ console.log('āœ… Insert result:', {
22
+ insertedId: insertResult1.insertedId,
23
+ acknowledged: insertResult1.acknowledged
24
+ });
25
+ console.log('');
26
+
27
+ // Test 2: Insert multiple documents
28
+ console.log('šŸ“ Test 2: Inserting multiple documents into "products" collection...');
29
+ const insertResult2 = await helper.insert('products', [
30
+ { name: 'Laptop', price: 999.99, category: 'Electronics', stock: 15 },
31
+ { name: 'Mouse', price: 29.99, category: 'Electronics', stock: 50 },
32
+ { name: 'Keyboard', price: 79.99, category: 'Electronics', stock: 30 }
33
+ ]);
34
+ console.log('āœ… Insert result:', {
35
+ insertedCount: insertResult2.insertedCount,
36
+ insertedIds: insertResult2.insertedIds
37
+ });
38
+ console.log('');
39
+
40
+ // Test 3: Load collection without query
41
+ console.log('šŸ“– Test 3: Loading all documents from "users" collection...');
42
+ const allUsers = await helper.loadCollection('users');
43
+ const usersArray = Array.isArray(allUsers) ? allUsers : allUsers.data;
44
+ console.log(`āœ… Found ${usersArray.length} user(s):`);
45
+ console.log(JSON.stringify(usersArray, null, 2));
46
+ console.log('');
47
+
48
+ // Test 4: Load collection with query
49
+ console.log('šŸ“– Test 4: Loading products with price > 50 from "products" collection...');
50
+ const expensiveProducts = await helper.loadCollection('products', {
51
+ price: { $gt: 50 }
52
+ });
53
+ const productsArray = Array.isArray(expensiveProducts) ? expensiveProducts : expensiveProducts.data;
54
+ console.log(`āœ… Found ${productsArray.length} product(s):`);
55
+ console.log(JSON.stringify(productsArray, null, 2));
56
+ console.log('');
57
+
58
+ // Test 5: Update single document
59
+ console.log('šŸ”„ Test 5: Updating user age...');
60
+ const updateResult1 = await helper.update(
61
+ 'users',
62
+ { name: 'John Doe' },
63
+ { $set: { age: 31, updatedAt: new Date() } }
64
+ );
65
+ console.log('āœ… Update result:', {
66
+ matchedCount: updateResult1.matchedCount,
67
+ modifiedCount: updateResult1.modifiedCount
68
+ });
69
+ console.log('');
70
+
71
+ // Test 6: Update multiple documents
72
+ console.log('šŸ”„ Test 6: Updating multiple products (reducing stock)...');
73
+ const updateResult2 = await helper.update(
74
+ 'products',
75
+ { category: 'Electronics' },
76
+ { $inc: { stock: -1 } },
77
+ { multi: true }
78
+ );
79
+ console.log('āœ… Update result:', {
80
+ matchedCount: updateResult2.matchedCount,
81
+ modifiedCount: updateResult2.modifiedCount
82
+ });
83
+ console.log('');
84
+
85
+ // Test 7: Load updated data
86
+ console.log('šŸ“– Test 7: Loading updated user data...');
87
+ const updatedUser = await helper.loadCollection('users', { name: 'John Doe' });
88
+ console.log('āœ… Updated user:');
89
+ console.log(JSON.stringify(updatedUser, null, 2));
90
+ console.log('');
91
+
92
+ // Test 8: Upsert (insert if not exists)
93
+ console.log('šŸ“ Test 8: Upserting a document (insert if not exists)...');
94
+ const upsertResult = await helper.update(
95
+ 'users',
96
+ { email: 'jane@example.com' },
97
+ {
98
+ $set: {
99
+ name: 'Jane Smith',
100
+ email: 'jane@example.com',
101
+ age: 25,
102
+ role: 'user'
103
+ }
104
+ },
105
+ { upsert: true }
106
+ );
107
+ console.log('āœ… Upsert result:', {
108
+ matchedCount: upsertResult.matchedCount,
109
+ modifiedCount: upsertResult.modifiedCount,
110
+ upsertedCount: upsertResult.upsertedCount,
111
+ upsertedId: upsertResult.upsertedId
112
+ });
113
+ console.log('');
114
+
115
+ // Test 9: Load all users after upsert
116
+ console.log('šŸ“– Test 9: Loading all users after upsert...');
117
+ const allUsersAfter = await helper.loadCollection('users');
118
+ console.log(`āœ… Found ${(allUsersAfter as any[]).length} user(s):`);
119
+ console.log(JSON.stringify(allUsersAfter, null, 2));
120
+ console.log('');
121
+
122
+ // Test 10: FindOne operation
123
+ console.log('šŸ” Test 10: Finding a single user by email...');
124
+ const singleUser = await helper.findOne('users', { email: 'john@example.com' });
125
+ console.log('āœ… Found user:');
126
+ console.log(JSON.stringify(singleUser, null, 2));
127
+ console.log('');
128
+
129
+ // Test 11: Count documents
130
+ console.log('šŸ”¢ Test 11: Counting documents...');
131
+ const userCount = await helper.countDocuments('users');
132
+ const productCount = await helper.countDocuments('products');
133
+ const estimatedCount = await helper.estimatedDocumentCount('products');
134
+ console.log(`āœ… User count: ${userCount}`);
135
+ console.log(`āœ… Product count: ${productCount}`);
136
+ console.log(`āœ… Estimated product count: ${estimatedCount}`);
137
+ console.log('');
138
+
139
+ // Test 12: Pagination
140
+ console.log('šŸ“„ Test 12: Testing pagination...');
141
+ const paginatedResult = await helper.loadCollection('products', {}, { page: 1, limit: 2, sort: { price: -1 } });
142
+ if ('data' in paginatedResult) {
143
+ console.log(`āœ… Page ${paginatedResult.page} of ${paginatedResult.totalPages}:`);
144
+ console.log(` Total: ${paginatedResult.total}, Showing: ${paginatedResult.data.length}`);
145
+ console.log(` Has next: ${paginatedResult.hasNext}, Has prev: ${paginatedResult.hasPrev}`);
146
+ console.log(' Products:');
147
+ console.log(JSON.stringify(paginatedResult.data, null, 2));
148
+ }
149
+ console.log('');
150
+
151
+ // Test 13: Aggregation pipeline
152
+ console.log('šŸ“Š Test 13: Testing aggregation pipeline...');
153
+ const aggregationResult = await helper.aggregate('products', [
154
+ { $match: { category: 'Electronics' } },
155
+ { $group: { _id: '$category', totalStock: { $sum: '$stock' }, avgPrice: { $avg: '$price' } } }
156
+ ]);
157
+ console.log('āœ… Aggregation result:');
158
+ console.log(JSON.stringify(aggregationResult, null, 2));
159
+ console.log('');
160
+
161
+ // Test 14: Index management
162
+ console.log('šŸ“‡ Test 14: Testing index management...');
163
+ const indexName = await helper.createIndex('products', { name: 1 }, { unique: false });
164
+ console.log(`āœ… Created index: ${indexName}`);
165
+ const indexes = await helper.listIndexes('products');
166
+ console.log(`āœ… Collection has ${indexes.length} index(es):`);
167
+ indexes.forEach(idx => console.log(` - ${idx.name}`));
168
+ console.log('');
169
+
170
+ // Test 15: Delete operation
171
+ console.log('šŸ—‘ļø Test 15: Testing delete operation...');
172
+ const deleteResult = await helper.delete('users', { email: 'jane@example.com' });
173
+ console.log('āœ… Delete result:', {
174
+ deletedCount: deleteResult.deletedCount,
175
+ acknowledged: deleteResult.acknowledged
176
+ });
177
+ const remainingUsers = await helper.countDocuments('users');
178
+ console.log(`āœ… Remaining users: ${remainingUsers}`);
179
+ console.log('');
180
+
181
+ // Test 16: Transaction (if supported)
182
+ console.log('šŸ’¼ Test 16: Testing transaction support...');
183
+ try {
184
+ await helper.withTransaction(async (session) => {
185
+ await helper.insert('users', { name: 'Transaction User', email: 'tx@example.com', age: 20 }, { session });
186
+ await helper.update('users', { email: 'tx@example.com' }, { $set: { role: 'user' } }, { session });
187
+ return 'Transaction completed';
188
+ });
189
+ console.log('āœ… Transaction executed successfully');
190
+ } catch (error) {
191
+ console.log(`āš ļø Transaction test skipped (may require replica set): ${error instanceof Error ? error.message : String(error)}`);
192
+ }
193
+ console.log('');
194
+
195
+ console.log('šŸŽ‰ All tests completed successfully!');
196
+
197
+ } catch (error) {
198
+ console.error('āŒ Test failed:', error instanceof Error ? error.message : String(error));
199
+ process.exit(1);
200
+ } finally {
201
+ console.log('\nšŸ”Œ Disconnecting from MongoDB...');
202
+ await helper.disconnect();
203
+ console.log('āœ… Disconnected successfully!');
204
+ }
205
+ }
206
+
207
+ // Run the test
208
+ testMongoHelper().catch(console.error);
209
+
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "commonjs",
5
+ "lib": ["ES2020"],
6
+ "outDir": "./dist",
7
+ "rootDir": "./src",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "resolveJsonModule": true,
13
+ "declaration": true,
14
+ "declarationMap": true,
15
+ "sourceMap": true,
16
+ "moduleResolution": "node"
17
+ },
18
+ "include": ["src/**/*"],
19
+ "exclude": ["node_modules", "dist"]
20
+ }
21
+