@push.rocks/smartmongo 2.1.0 → 3.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.
Files changed (109) hide show
  1. package/dist_ts/00_commitinfo_data.js +1 -1
  2. package/dist_ts/index.d.ts +1 -1
  3. package/dist_ts/index.js +3 -3
  4. package/dist_ts/tsmdb/engine/AggregationEngine.js +189 -0
  5. package/dist_ts/tsmdb/engine/IndexEngine.js +376 -0
  6. package/dist_ts/tsmdb/engine/QueryEngine.js +271 -0
  7. package/dist_ts/{congodb → tsmdb}/engine/TransactionEngine.d.ts +1 -1
  8. package/dist_ts/tsmdb/engine/TransactionEngine.js +287 -0
  9. package/dist_ts/tsmdb/engine/UpdateEngine.js +461 -0
  10. package/dist_ts/{congodb/errors/CongoErrors.d.ts → tsmdb/errors/TsmdbErrors.d.ts} +16 -16
  11. package/dist_ts/tsmdb/errors/TsmdbErrors.js +155 -0
  12. package/dist_ts/{congodb → tsmdb}/index.d.ts +4 -4
  13. package/dist_ts/tsmdb/index.js +26 -0
  14. package/dist_ts/{congodb → tsmdb}/server/CommandRouter.d.ts +4 -4
  15. package/dist_ts/tsmdb/server/CommandRouter.js +132 -0
  16. package/dist_ts/{congodb/server/CongoServer.d.ts → tsmdb/server/TsmdbServer.d.ts} +6 -6
  17. package/dist_ts/tsmdb/server/TsmdbServer.js +227 -0
  18. package/dist_ts/{congodb → tsmdb}/server/WireProtocol.d.ts +1 -1
  19. package/dist_ts/tsmdb/server/WireProtocol.js +298 -0
  20. package/dist_ts/{congodb → tsmdb}/server/handlers/AdminHandler.d.ts +1 -1
  21. package/dist_ts/tsmdb/server/handlers/AdminHandler.js +568 -0
  22. package/dist_ts/{congodb → tsmdb}/server/handlers/AggregateHandler.d.ts +1 -1
  23. package/dist_ts/tsmdb/server/handlers/AggregateHandler.js +277 -0
  24. package/dist_ts/{congodb → tsmdb}/server/handlers/DeleteHandler.d.ts +1 -1
  25. package/dist_ts/tsmdb/server/handlers/DeleteHandler.js +83 -0
  26. package/dist_ts/{congodb → tsmdb}/server/handlers/FindHandler.d.ts +1 -1
  27. package/dist_ts/tsmdb/server/handlers/FindHandler.js +261 -0
  28. package/dist_ts/{congodb → tsmdb}/server/handlers/HelloHandler.d.ts +1 -1
  29. package/dist_ts/{congodb → tsmdb}/server/handlers/HelloHandler.js +2 -2
  30. package/dist_ts/{congodb → tsmdb}/server/handlers/IndexHandler.d.ts +1 -1
  31. package/dist_ts/tsmdb/server/handlers/IndexHandler.js +183 -0
  32. package/dist_ts/{congodb → tsmdb}/server/handlers/InsertHandler.d.ts +1 -1
  33. package/dist_ts/tsmdb/server/handlers/InsertHandler.js +76 -0
  34. package/dist_ts/{congodb → tsmdb}/server/handlers/UpdateHandler.d.ts +1 -1
  35. package/dist_ts/tsmdb/server/handlers/UpdateHandler.js +270 -0
  36. package/dist_ts/tsmdb/server/handlers/index.js +10 -0
  37. package/dist_ts/{congodb → tsmdb}/server/index.d.ts +2 -2
  38. package/dist_ts/tsmdb/server/index.js +7 -0
  39. package/dist_ts/{congodb → tsmdb}/storage/FileStorageAdapter.d.ts +2 -2
  40. package/dist_ts/tsmdb/storage/FileStorageAdapter.js +396 -0
  41. package/dist_ts/{congodb → tsmdb}/storage/IStorageAdapter.d.ts +2 -2
  42. package/dist_ts/{congodb → tsmdb}/storage/IStorageAdapter.js +1 -1
  43. package/dist_ts/{congodb → tsmdb}/storage/MemoryStorageAdapter.d.ts +2 -2
  44. package/dist_ts/tsmdb/storage/MemoryStorageAdapter.js +367 -0
  45. package/dist_ts/{congodb → tsmdb}/storage/OpLog.d.ts +1 -1
  46. package/dist_ts/tsmdb/storage/OpLog.js +221 -0
  47. package/dist_ts/tsmdb/tsmdb.plugins.js +14 -0
  48. package/dist_ts/{congodb → tsmdb}/types/interfaces.d.ts +3 -3
  49. package/dist_ts/{congodb → tsmdb}/types/interfaces.js +1 -1
  50. package/package.json +1 -1
  51. package/readme.hints.md +7 -12
  52. package/readme.md +398 -44
  53. package/ts/00_commitinfo_data.ts +1 -1
  54. package/ts/index.ts +2 -2
  55. package/ts/{congodb → tsmdb}/engine/AggregationEngine.ts +1 -1
  56. package/ts/{congodb → tsmdb}/engine/IndexEngine.ts +7 -7
  57. package/ts/{congodb → tsmdb}/engine/QueryEngine.ts +1 -1
  58. package/ts/{congodb → tsmdb}/engine/TransactionEngine.ts +12 -12
  59. package/ts/{congodb → tsmdb}/engine/UpdateEngine.ts +1 -1
  60. package/ts/{congodb/errors/CongoErrors.ts → tsmdb/errors/TsmdbErrors.ts} +34 -34
  61. package/ts/{congodb → tsmdb}/index.ts +7 -7
  62. package/ts/{congodb → tsmdb}/server/CommandRouter.ts +5 -5
  63. package/ts/{congodb/server/CongoServer.ts → tsmdb/server/TsmdbServer.ts} +8 -8
  64. package/ts/{congodb → tsmdb}/server/WireProtocol.ts +1 -1
  65. package/ts/{congodb → tsmdb}/server/handlers/AdminHandler.ts +6 -6
  66. package/ts/{congodb → tsmdb}/server/handlers/AggregateHandler.ts +1 -1
  67. package/ts/{congodb → tsmdb}/server/handlers/DeleteHandler.ts +1 -1
  68. package/ts/{congodb → tsmdb}/server/handlers/FindHandler.ts +1 -1
  69. package/ts/{congodb → tsmdb}/server/handlers/HelloHandler.ts +1 -1
  70. package/ts/{congodb → tsmdb}/server/handlers/IndexHandler.ts +1 -1
  71. package/ts/{congodb → tsmdb}/server/handlers/InsertHandler.ts +1 -1
  72. package/ts/{congodb → tsmdb}/server/handlers/UpdateHandler.ts +1 -1
  73. package/ts/{congodb → tsmdb}/server/index.ts +2 -2
  74. package/ts/{congodb → tsmdb}/storage/FileStorageAdapter.ts +2 -2
  75. package/ts/{congodb → tsmdb}/storage/IStorageAdapter.ts +2 -2
  76. package/ts/{congodb → tsmdb}/storage/MemoryStorageAdapter.ts +2 -2
  77. package/ts/{congodb → tsmdb}/storage/OpLog.ts +1 -1
  78. package/ts/{congodb → tsmdb}/types/interfaces.ts +3 -3
  79. package/dist_ts/congodb/congodb.plugins.js +0 -14
  80. package/dist_ts/congodb/engine/AggregationEngine.js +0 -189
  81. package/dist_ts/congodb/engine/IndexEngine.js +0 -376
  82. package/dist_ts/congodb/engine/QueryEngine.js +0 -271
  83. package/dist_ts/congodb/engine/TransactionEngine.js +0 -287
  84. package/dist_ts/congodb/engine/UpdateEngine.js +0 -461
  85. package/dist_ts/congodb/errors/CongoErrors.js +0 -155
  86. package/dist_ts/congodb/index.js +0 -26
  87. package/dist_ts/congodb/server/CommandRouter.js +0 -132
  88. package/dist_ts/congodb/server/CongoServer.js +0 -227
  89. package/dist_ts/congodb/server/WireProtocol.js +0 -298
  90. package/dist_ts/congodb/server/handlers/AdminHandler.js +0 -568
  91. package/dist_ts/congodb/server/handlers/AggregateHandler.js +0 -277
  92. package/dist_ts/congodb/server/handlers/DeleteHandler.js +0 -83
  93. package/dist_ts/congodb/server/handlers/FindHandler.js +0 -261
  94. package/dist_ts/congodb/server/handlers/IndexHandler.js +0 -183
  95. package/dist_ts/congodb/server/handlers/InsertHandler.js +0 -76
  96. package/dist_ts/congodb/server/handlers/UpdateHandler.js +0 -270
  97. package/dist_ts/congodb/server/handlers/index.js +0 -10
  98. package/dist_ts/congodb/server/index.js +0 -7
  99. package/dist_ts/congodb/storage/FileStorageAdapter.js +0 -396
  100. package/dist_ts/congodb/storage/MemoryStorageAdapter.js +0 -367
  101. package/dist_ts/congodb/storage/OpLog.js +0 -221
  102. /package/dist_ts/{congodb → tsmdb}/engine/AggregationEngine.d.ts +0 -0
  103. /package/dist_ts/{congodb → tsmdb}/engine/IndexEngine.d.ts +0 -0
  104. /package/dist_ts/{congodb → tsmdb}/engine/QueryEngine.d.ts +0 -0
  105. /package/dist_ts/{congodb → tsmdb}/engine/UpdateEngine.d.ts +0 -0
  106. /package/dist_ts/{congodb → tsmdb}/server/handlers/index.d.ts +0 -0
  107. /package/dist_ts/{congodb/congodb.plugins.d.ts → tsmdb/tsmdb.plugins.d.ts} +0 -0
  108. /package/ts/{congodb → tsmdb}/server/handlers/index.ts +0 -0
  109. /package/ts/{congodb/congodb.plugins.ts → tsmdb/tsmdb.plugins.ts} +0 -0
@@ -1,9 +1,9 @@
1
- import type * as plugins from '../congodb.plugins.js';
1
+ import type * as plugins from '../tsmdb.plugins.js';
2
2
  export type Document = Record<string, any>;
3
3
  export interface WithId<TSchema> {
4
4
  _id: plugins.bson.ObjectId;
5
5
  }
6
- export interface ICongoClientOptions {
6
+ export interface ITsmdbClientOptions {
7
7
  /** Storage adapter type: 'memory' or 'file' */
8
8
  storageType?: 'memory' | 'file';
9
9
  /** Path for file-based storage */
@@ -14,7 +14,7 @@ export interface ICongoClientOptions {
14
14
  persistPath?: string;
15
15
  }
16
16
  export interface IParsedConnectionString {
17
- protocol: 'congo';
17
+ protocol: 'tsmdb';
18
18
  storageType: 'memory' | 'file';
19
19
  options: {
20
20
  persist?: string;
@@ -1,2 +1,2 @@
1
1
  export {};
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJmYWNlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3RzL2NvbmdvZGIvdHlwZXMvaW50ZXJmYWNlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIn0=
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJmYWNlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3RzL3RzbWRiL3R5cGVzL2ludGVyZmFjZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@push.rocks/smartmongo",
3
- "version": "2.1.0",
3
+ "version": "3.0.0",
4
4
  "private": false,
5
5
  "description": "A module for creating and managing a local MongoDB instance for testing purposes.",
6
6
  "main": "dist_ts/index.js",
package/readme.hints.md CHANGED
@@ -9,21 +9,21 @@
9
9
  - **Why:** Deno wraps CommonJS exports in a `default` property, so default imports are required
10
10
  - Fixed in version 2.0.13 (changed from `import * as mongoPlugin`)
11
11
 
12
- ## CongoDB - MongoDB Wire Protocol Server
12
+ ## TsmDB - MongoDB Wire Protocol Server
13
13
 
14
14
  ### Architecture
15
- CongoDB implements the MongoDB binary wire protocol (OP_MSG, OP_QUERY) allowing official MongoDB drivers to connect directly.
15
+ TsmDB implements the MongoDB binary wire protocol (OP_MSG, OP_QUERY) allowing official MongoDB drivers to connect directly.
16
16
 
17
17
  ```
18
- Official MongoClient → TCP (wire protocol) → CongoServer → Engines → Storage
18
+ Official MongoClient → TCP (wire protocol) → TsmdbServer → Engines → Storage
19
19
  (mongodb npm) OP_MSG/BSON (port)
20
20
  ```
21
21
 
22
22
  ### Module Structure
23
23
  ```
24
- ts/congodb/
24
+ ts/tsmdb/
25
25
  ├── server/ # Wire protocol server
26
- │ ├── CongoServer.ts # TCP server, connection handling
26
+ │ ├── TsmdbServer.ts # TCP server, connection handling
27
27
  │ ├── WireProtocol.ts # OP_MSG/OP_QUERY parsing & encoding
28
28
  │ ├── CommandRouter.ts # Route commands to handlers
29
29
  │ └── handlers/ # Command implementations
@@ -53,11 +53,11 @@ ts/congodb/
53
53
 
54
54
  ### Usage Example
55
55
  ```typescript
56
- import { CongoServer } from '@push.rocks/smartmongo/congodb';
56
+ import { TsmdbServer } from '@push.rocks/smartmongo/tsmdb';
57
57
  import { MongoClient } from 'mongodb';
58
58
 
59
59
  // Start server
60
- const server = new CongoServer({ port: 27117 });
60
+ const server = new TsmdbServer({ port: 27117 });
61
61
  await server.start();
62
62
 
63
63
  // Connect with official MongoDB driver
@@ -82,8 +82,3 @@ await server.stop();
82
82
  - **Aggregation**: aggregate, count, distinct
83
83
  - **Indexes**: createIndexes, dropIndexes, listIndexes
84
84
  - **Admin**: ping, listDatabases, listCollections, drop, dropDatabase, create, serverStatus, buildInfo
85
-
86
- ### Notes
87
- - The old CongoClient/CongoDb/CongoCollection classes have been removed
88
- - Use the official `mongodb` npm package's MongoClient instead
89
- - Server supports MongoDB wire protocol versions 0-21 (MongoDB 3.6 through 7.0 compatible)
package/readme.md CHANGED
@@ -1,104 +1,458 @@
1
1
  # @push.rocks/smartmongo
2
2
 
3
- create a local mongodb for testing
3
+ A powerful MongoDB toolkit for testing and development — featuring both a real MongoDB memory server (**SmartMongo**) and an ultra-fast, lightweight wire-protocol-compatible in-memory database server (**TsmDB**). 🚀
4
4
 
5
5
  ## Install
6
6
 
7
- To start using @push.rocks/smartmongo in your project, you first need to install it via npm. You can do this by running the following command in your terminal:
8
-
9
7
  ```bash
10
8
  npm install @push.rocks/smartmongo --save-dev
9
+ # or
10
+ pnpm add -D @push.rocks/smartmongo
11
+ ```
12
+
13
+ ## Issue Reporting and Security
14
+
15
+ For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
16
+
17
+ ## Overview
18
+
19
+ `@push.rocks/smartmongo` provides two powerful approaches for MongoDB in testing and development:
20
+
21
+ | Feature | SmartMongo | TsmDB |
22
+ |---------|------------|---------|
23
+ | **Type** | Real MongoDB (memory server) | Pure TypeScript wire protocol server |
24
+ | **Speed** | ~2-5s startup | ⚡ Instant startup (~5ms) |
25
+ | **Compatibility** | 100% MongoDB | MongoDB driver compatible |
26
+ | **Dependencies** | Downloads MongoDB binary | Zero external dependencies |
27
+ | **Replication** | ✅ Full replica set support | Single node emulation |
28
+ | **Use Case** | Integration testing | Unit testing, CI/CD |
29
+ | **Persistence** | Dump to directory | Optional file/memory persistence |
30
+
31
+ ## 🚀 Quick Start
32
+
33
+ ### Option 1: SmartMongo (Real MongoDB)
34
+
35
+ Spin up a real MongoDB replica set in memory — perfect for integration tests that need full MongoDB compatibility.
36
+
37
+ ```typescript
38
+ import { SmartMongo } from '@push.rocks/smartmongo';
39
+
40
+ // Start a MongoDB replica set
41
+ const mongo = await SmartMongo.createAndStart();
42
+
43
+ // Get connection details
44
+ const descriptor = await mongo.getMongoDescriptor();
45
+ console.log(descriptor.mongoDbUrl); // mongodb://127.0.0.1:xxxxx/...
46
+
47
+ // Use with your MongoDB client or ORM
48
+ // ... run your tests ...
49
+
50
+ // Clean up
51
+ await mongo.stop();
11
52
  ```
12
53
 
13
- This will add `@push.rocks/smartmongo` as a development dependency to your project because it's typically used for testing purposes.
54
+ ### Option 2: TsmDB (Wire Protocol Server)
55
+
56
+ A lightweight, pure TypeScript MongoDB-compatible server that speaks the wire protocol — use the official `mongodb` driver directly!
14
57
 
15
- ## Usage
58
+ ```typescript
59
+ import { tsmdb } from '@push.rocks/smartmongo';
60
+ import { MongoClient } from 'mongodb';
61
+
62
+ // Start TsmDB server
63
+ const server = new tsmdb.TsmdbServer({ port: 27017 });
64
+ await server.start();
65
+
66
+ // Connect with the official MongoDB driver!
67
+ const client = new MongoClient('mongodb://127.0.0.1:27017');
68
+ await client.connect();
16
69
 
17
- The `@push.rocks/smartmongo` package provides a convenient way to spin up a local MongoDB instance, primarily for testing purposes. It's designed to simplify the process of configuring and managing a MongoDB replica set during development or in CI/CD pipelines. Below, we present a comprehensive guide on how to utilize the full feature set of this module, employing ESM syntax and TypeScript.
70
+ // Use exactly like real MongoDB
71
+ const db = client.db('myapp');
72
+ await db.collection('users').insertOne({ name: 'Alice', age: 30 });
73
+
74
+ const user = await db.collection('users').findOne({ name: 'Alice' });
75
+ console.log(user); // { _id: ObjectId(...), name: 'Alice', age: 30 }
76
+
77
+ // Clean up
78
+ await client.close();
79
+ await server.stop();
80
+ ```
18
81
 
19
- ### Setting Up
82
+ ## 📖 SmartMongo API
20
83
 
21
- To get started, you must first import the `SmartMongo` class from the package. This class is responsible for handling the MongoDB instances.
84
+ ### Creating an Instance
22
85
 
23
86
  ```typescript
24
87
  import { SmartMongo } from '@push.rocks/smartmongo';
88
+
89
+ // Default: single replica
90
+ const mongo = await SmartMongo.createAndStart();
91
+
92
+ // Multiple replicas for testing replication
93
+ const mongo = await SmartMongo.createAndStart(3);
94
+ ```
95
+
96
+ ### Getting Connection Details
97
+
98
+ ```typescript
99
+ const descriptor = await mongo.getMongoDescriptor();
100
+ // {
101
+ // mongoDbName: 'smartmongo_testdatabase',
102
+ // mongoDbUrl: 'mongodb://127.0.0.1:xxxxx/?replicaSet=testset'
103
+ // }
104
+ ```
105
+
106
+ ### Stopping & Cleanup
107
+
108
+ ```typescript
109
+ // Simple stop (data discarded)
110
+ await mongo.stop();
111
+
112
+ // Stop and dump data to disk for inspection
113
+ await mongo.stopAndDumpToDir('./test-data');
114
+
115
+ // With custom file naming
116
+ await mongo.stopAndDumpToDir('./test-data', (doc) => `${doc.collection}-${doc._id}.bson`);
117
+ ```
118
+
119
+ ## 🔧 TsmDB API
120
+
121
+ ### Server Configuration
122
+
123
+ ```typescript
124
+ import { tsmdb } from '@push.rocks/smartmongo';
125
+
126
+ const server = new tsmdb.TsmdbServer({
127
+ port: 27017, // Default MongoDB port
128
+ host: '127.0.0.1', // Bind address
129
+ storage: 'memory', // 'memory' or 'file'
130
+ storagePath: './data', // For file-based storage
131
+ });
132
+
133
+ await server.start();
134
+ console.log(server.getConnectionUri()); // mongodb://127.0.0.1:27017
135
+
136
+ // Server properties
137
+ console.log(server.running); // true
138
+ console.log(server.getUptime()); // seconds
139
+ console.log(server.getConnectionCount()); // active connections
140
+
141
+ await server.stop();
142
+ ```
143
+
144
+ ### Supported MongoDB Operations
145
+
146
+ TsmDB supports the core MongoDB operations via the wire protocol:
147
+
148
+ #### 🔹 CRUD Operations
149
+ ```typescript
150
+ // Insert
151
+ await collection.insertOne({ name: 'Bob' });
152
+ await collection.insertMany([{ a: 1 }, { a: 2 }]);
153
+
154
+ // Find
155
+ const doc = await collection.findOne({ name: 'Bob' });
156
+ const docs = await collection.find({ age: { $gte: 18 } }).toArray();
157
+
158
+ // Update
159
+ await collection.updateOne({ name: 'Bob' }, { $set: { age: 25 } });
160
+ await collection.updateMany({ active: false }, { $set: { archived: true } });
161
+
162
+ // Delete
163
+ await collection.deleteOne({ name: 'Bob' });
164
+ await collection.deleteMany({ archived: true });
165
+
166
+ // Replace
167
+ await collection.replaceOne({ _id: id }, { name: 'New Bob', age: 30 });
168
+
169
+ // Find and Modify
170
+ const result = await collection.findOneAndUpdate(
171
+ { name: 'Bob' },
172
+ { $inc: { visits: 1 } },
173
+ { returnDocument: 'after' }
174
+ );
25
175
  ```
26
176
 
27
- ### Creating and Starting a MongoDB Instance
177
+ #### 🔹 Query Operators
178
+ ```typescript
179
+ // Comparison
180
+ { age: { $eq: 25 } }
181
+ { age: { $ne: 25 } }
182
+ { age: { $gt: 18, $lt: 65 } }
183
+ { age: { $gte: 18, $lte: 65 } }
184
+ { status: { $in: ['active', 'pending'] } }
185
+ { status: { $nin: ['deleted'] } }
186
+
187
+ // Logical
188
+ { $and: [{ age: { $gte: 18 } }, { active: true }] }
189
+ { $or: [{ status: 'active' }, { admin: true }] }
190
+ { $not: { status: 'deleted' } }
191
+
192
+ // Element
193
+ { email: { $exists: true } }
194
+ { type: { $type: 'string' } }
195
+
196
+ // Array
197
+ { tags: { $all: ['mongodb', 'database'] } }
198
+ { scores: { $elemMatch: { $gte: 80, $lt: 90 } } }
199
+ { tags: { $size: 3 } }
200
+ ```
28
201
 
29
- With `SmartMongo`, you can easily create and start a MongoDB replica set. You can specify the number of replica instances; however, if not specified, it defaults to 1.
202
+ #### 🔹 Update Operators
203
+ ```typescript
204
+ { $set: { name: 'New Name' } }
205
+ { $unset: { tempField: '' } }
206
+ { $inc: { count: 1 } }
207
+ { $mul: { price: 1.1 } }
208
+ { $min: { lowScore: 50 } }
209
+ { $max: { highScore: 100 } }
210
+ { $push: { tags: 'new-tag' } }
211
+ { $pull: { tags: 'old-tag' } }
212
+ { $addToSet: { tags: 'unique-tag' } }
213
+ { $pop: { queue: 1 } } // Remove last
214
+ { $pop: { queue: -1 } } // Remove first
215
+ ```
30
216
 
217
+ #### 🔹 Aggregation Pipeline
31
218
  ```typescript
32
- async function setupMongoDB() {
33
- const smartMongoInstance = await SmartMongo.createAndStart(1); // Number of replicas is optional
34
- return smartMongoInstance;
35
- }
219
+ const results = await collection.aggregate([
220
+ { $match: { status: 'active' } },
221
+ { $group: { _id: '$category', total: { $sum: '$amount' } } },
222
+ { $sort: { total: -1 } },
223
+ { $limit: 10 },
224
+ { $project: { category: '$_id', total: 1, _id: 0 } }
225
+ ]).toArray();
226
+ ```
36
227
 
37
- const myDbInstance = await setupMongoDB();
228
+ Supported stages: `$match`, `$project`, `$group`, `$sort`, `$limit`, `$skip`, `$unwind`, `$lookup`, `$addFields`, `$count`, `$facet`, and more.
229
+
230
+ #### 🔹 Index Operations
231
+ ```typescript
232
+ await collection.createIndex({ email: 1 }, { unique: true });
233
+ await collection.createIndex({ name: 1, age: -1 });
234
+ const indexes = await collection.listIndexes().toArray();
235
+ await collection.dropIndex('email_1');
38
236
  ```
39
237
 
40
- After invoking `createAndStart`, an instance of MongoDB is spun up and is ready for use. The `createAndStart` function returns a `SmartMongo` instance which can be interacted with for further operations.
238
+ #### 🔹 Database Operations
239
+ ```typescript
240
+ // List databases
241
+ const dbs = await client.db().admin().listDatabases();
242
+
243
+ // List collections
244
+ const collections = await db.listCollections().toArray();
41
245
 
42
- ### Accessing MongoDB Connection Information
246
+ // Create/drop collections
247
+ await db.createCollection('newcollection');
248
+ await db.dropCollection('oldcollection');
43
249
 
44
- After instantiation, you might want to connect your application or test suite to the MongoDB instance. The `getMongoDescriptor` method facilitates this by providing essential connection details.
250
+ // Drop database
251
+ await db.dropDatabase();
252
+ ```
45
253
 
254
+ #### 🔹 Count & Distinct
46
255
  ```typescript
47
- const mongoDescriptor = await myDbInstance.getMongoDescriptor();
48
- console.log(mongoDescriptor.mongoDbUrl); // Use this URL to connect with Mongoose or MongoDB clients.
256
+ // Count documents
257
+ const total = await collection.countDocuments({});
258
+ const active = await collection.countDocuments({ status: 'active' });
259
+ const estimated = await collection.estimatedDocumentCount();
260
+
261
+ // Distinct values
262
+ const departments = await collection.distinct('department');
263
+ const activeDepts = await collection.distinct('department', { status: 'active' });
49
264
  ```
50
265
 
51
- ### Stopping and Cleaning Up
266
+ #### 🔹 Bulk Operations
267
+ ```typescript
268
+ const result = await collection.bulkWrite([
269
+ { insertOne: { document: { name: 'Bulk1' } } },
270
+ { updateOne: { filter: { name: 'John' }, update: { $set: { bulk: true } } } },
271
+ { deleteOne: { filter: { name: 'Expired' } } },
272
+ { replaceOne: { filter: { _id: id }, replacement: { name: 'Replaced' } } }
273
+ ]);
274
+
275
+ console.log(result.insertedCount); // 1
276
+ console.log(result.modifiedCount); // 1
277
+ console.log(result.deletedCount); // 1
278
+ ```
52
279
 
53
- Once your tests have completed or you're done using the MongoDB instance, it’s crucial to properly stop and clean up the resources. `@push.rocks/smartmongo` provides two methods for this purpose:
280
+ ### Storage Adapters
54
281
 
55
- 1. **stop()**: Stops the MongoDB instance without persisting any data.
282
+ TsmDB supports pluggable storage:
56
283
 
57
- ```typescript
58
- await myDbInstance.stop();
59
- ```
284
+ ```typescript
285
+ // In-memory (default) - fast, data lost on stop
286
+ const server = new tsmdb.TsmdbServer({ storage: 'memory' });
287
+
288
+ // In-memory with persistence - periodic snapshots to disk
289
+ const server = new tsmdb.TsmdbServer({
290
+ storage: 'memory',
291
+ persistPath: './data/snapshot.json',
292
+ persistIntervalMs: 30000 // Save every 30 seconds
293
+ });
60
294
 
61
- 2. **stopAndDumpToDir(dirPath)**: Stops the MongoDB instance and persists the data to the specified directory. This is useful if you need to examine the data post-test or reuse it in subsequent runs.
295
+ // File-based - persistent storage
296
+ const server = new tsmdb.TsmdbServer({
297
+ storage: 'file',
298
+ storagePath: './data/tsmdb'
299
+ });
300
+ ```
62
301
 
63
- ```typescript
64
- await myDbInstance.stopAndDumpToDir('./path/to/dump');
65
- ```
302
+ ### 📋 Supported Wire Protocol Commands
66
303
 
67
- ### Advanced Usage
304
+ | Category | Commands |
305
+ |----------|----------|
306
+ | **Handshake** | `hello`, `isMaster` |
307
+ | **CRUD** | `find`, `insert`, `update`, `delete`, `findAndModify`, `getMore`, `killCursors` |
308
+ | **Aggregation** | `aggregate`, `count`, `distinct` |
309
+ | **Indexes** | `createIndexes`, `dropIndexes`, `listIndexes` |
310
+ | **Admin** | `ping`, `listDatabases`, `listCollections`, `drop`, `dropDatabase`, `create`, `serverStatus`, `buildInfo` |
68
311
 
69
- `@push.rocks/smartmongo` also provides advanced features for dumping the database and configuring MongoDB replica sets. These features can be particularly useful for complex testing scenarios or when specific MongoDB behaviors need to be emulated.
312
+ TsmDB supports MongoDB wire protocol versions 0-21, compatible with MongoDB 3.6 through 7.0 drivers.
70
313
 
71
- #### Dumping Data
314
+ ## 🧪 Testing Examples
72
315
 
73
- To dump the MongoDB data for inspection or backup purposes, use the `stopAndDumpToDir` method. This method optionally takes a function to customize the naming scheme of the dumped files based on the document content.
316
+ ### Jest/Mocha with TsmDB
74
317
 
75
318
  ```typescript
76
- await myDbInstance.stopAndDumpToDir('./path/to/dump', (doc) => {
77
- return `customNameBasedOnDoc-${doc._id}.bson`;
319
+ import { tsmdb } from '@push.rocks/smartmongo';
320
+ import { MongoClient } from 'mongodb';
321
+
322
+ let server: tsmdb.TsmdbServer;
323
+ let client: MongoClient;
324
+ let db: Db;
325
+
326
+ beforeAll(async () => {
327
+ server = new tsmdb.TsmdbServer({ port: 27117 });
328
+ await server.start();
329
+
330
+ client = new MongoClient('mongodb://127.0.0.1:27117');
331
+ await client.connect();
332
+ db = client.db('test');
333
+ });
334
+
335
+ afterAll(async () => {
336
+ await client.close();
337
+ await server.stop();
338
+ });
339
+
340
+ beforeEach(async () => {
341
+ // Clean slate for each test
342
+ await db.dropDatabase();
343
+ });
344
+
345
+ test('should insert and find user', async () => {
346
+ const users = db.collection('users');
347
+ await users.insertOne({ name: 'Alice', email: 'alice@example.com' });
348
+
349
+ const user = await users.findOne({ name: 'Alice' });
350
+ expect(user?.email).toBe('alice@example.com');
78
351
  });
79
352
  ```
80
353
 
81
- Using `@push.rocks/smartmongo` significantly simplifies the process of managing MongoDB instances for local testing environments. It abstracts away the complexity of starting, operating, and tearing down MongoDB replica sets, allowing developers to focus on building and testing their applications.
354
+ ### With @push.rocks/tapbundle
82
355
 
83
- ### Conclusion
356
+ ```typescript
357
+ import { expect, tap } from '@git.zone/tstest/tapbundle';
358
+ import { tsmdb } from '@push.rocks/smartmongo';
359
+ import { MongoClient } from 'mongodb';
360
+
361
+ let server: tsmdb.TsmdbServer;
362
+ let client: MongoClient;
363
+
364
+ tap.test('setup', async () => {
365
+ server = new tsmdb.TsmdbServer({ port: 27117 });
366
+ await server.start();
367
+ client = new MongoClient('mongodb://127.0.0.1:27117');
368
+ await client.connect();
369
+ });
370
+
371
+ tap.test('should perform CRUD operations', async () => {
372
+ const db = client.db('test');
373
+ const col = db.collection('items');
84
374
 
85
- `@push.rocks/smartmongo` serves as a powerful tool in a developer's arsenal for efficiently configuring, running, and managing MongoDB instances in testing scenarios. By following the above guide, developers can leverage MongoDB in their projects with minimal setup and gain valuable insights into their applications' data interactions in a controlled and reproducible environment.
375
+ // Create
376
+ const result = await col.insertOne({ name: 'Widget', price: 9.99 });
377
+ expect(result.insertedId).toBeTruthy();
378
+
379
+ // Read
380
+ const item = await col.findOne({ name: 'Widget' });
381
+ expect(item?.price).toEqual(9.99);
382
+
383
+ // Update
384
+ await col.updateOne({ name: 'Widget' }, { $set: { price: 12.99 } });
385
+ const updated = await col.findOne({ name: 'Widget' });
386
+ expect(updated?.price).toEqual(12.99);
387
+
388
+ // Delete
389
+ await col.deleteOne({ name: 'Widget' });
390
+ const deleted = await col.findOne({ name: 'Widget' });
391
+ expect(deleted).toBeNull();
392
+ });
393
+
394
+ tap.test('teardown', async () => {
395
+ await client.close();
396
+ await server.stop();
397
+ });
398
+
399
+ export default tap.start();
400
+ ```
401
+
402
+ ## 🏗️ Architecture
403
+
404
+ ### TsmDB Wire Protocol Stack
405
+
406
+ ```
407
+ ┌─────────────────────────────────────────────────────────────┐
408
+ │ Official MongoDB Driver │
409
+ │ (mongodb npm) │
410
+ └─────────────────────────┬───────────────────────────────────┘
411
+ │ TCP + OP_MSG/BSON
412
+
413
+ ┌─────────────────────────────────────────────────────────────┐
414
+ │ TsmdbServer │
415
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
416
+ │ │ WireProtocol │→ │CommandRouter │→ │ Handlers │ │
417
+ │ │ (OP_MSG) │ │ │ │ (Find, Insert..) │ │
418
+ │ └──────────────┘ └──────────────┘ └──────────────────┘ │
419
+ └─────────────────────────┬───────────────────────────────────┘
420
+
421
+
422
+ ┌─────────────────────────────────────────────────────────────┐
423
+ │ Engines │
424
+ │ ┌───────────┐ ┌────────────┐ ┌────────────┐ ┌───────────┐ │
425
+ │ │ Query │ │ Update │ │Aggregation │ │ Index │ │
426
+ │ │ Engine │ │ Engine │ │ Engine │ │ Engine │ │
427
+ │ └───────────┘ └────────────┘ └────────────┘ └───────────┘ │
428
+ └─────────────────────────┬───────────────────────────────────┘
429
+
430
+
431
+ ┌─────────────────────────────────────────────────────────────┐
432
+ │ Storage Adapters │
433
+ │ ┌──────────────────┐ ┌──────────────────┐ │
434
+ │ │ MemoryStorage │ │ FileStorage │ │
435
+ │ └──────────────────┘ └──────────────────┘ │
436
+ └─────────────────────────────────────────────────────────────┘
437
+ ```
86
438
 
87
439
  ## License and Legal Information
88
440
 
89
- This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
441
+ This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
90
442
 
91
443
  **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
92
444
 
93
445
  ### Trademarks
94
446
 
95
- This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
447
+ This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
448
+
449
+ Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
96
450
 
97
451
  ### Company Information
98
452
 
99
- Task Venture Capital GmbH
100
- Registered at District court Bremen HRB 35230 HB, Germany
453
+ Task Venture Capital GmbH
454
+ Registered at District Court Bremen HRB 35230 HB, Germany
101
455
 
102
- For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
456
+ For any legal inquiries or further information, please contact us via email at hello@task.vc.
103
457
 
104
458
  By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartmongo',
6
- version: '2.1.0',
6
+ version: '3.0.0',
7
7
  description: 'A module for creating and managing a local MongoDB instance for testing purposes.'
8
8
  }
package/ts/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { commitinfo } from './00_commitinfo_data.js';
2
2
  import * as plugins from './smartmongo.plugins.js';
3
3
 
4
- // Export CongoDB module
5
- export * as congodb from './congodb/index.js';
4
+ // Export TsmDB module
5
+ export * as tsmdb from './tsmdb/index.js';
6
6
 
7
7
  export class SmartMongo {
8
8
  // STATIC
@@ -1,4 +1,4 @@
1
- import * as plugins from '../congodb.plugins.js';
1
+ import * as plugins from '../tsmdb.plugins.js';
2
2
  import type { Document, IStoredDocument, IAggregateOptions } from '../types/interfaces.js';
3
3
 
4
4
  // Import mingo Aggregator