@trust0/ridb-mongodb 0.0.2 → 0.0.3

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/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ ## 0.0.3 (2025-07-22)
2
+
3
+ ### 🩹 Fixes
4
+
5
+ - current structure doesn't manage examples very well will figure out later ([bcb8934](https://github.com/trust0-project/RIDB/commit/bcb8934))
6
+ - specify packages ([b49617b](https://github.com/trust0-project/RIDB/commit/b49617b))
7
+ - mongodb improvement ([3f89e54](https://github.com/trust0-project/RIDB/commit/3f89e54))
8
+
9
+ ### 🧱 Updated Dependencies
10
+
11
+ - Updated @trust0/ridb to 1.5.36
12
+
13
+ ### ❤️ Thank You
14
+
15
+ - Javier Ribó
16
+
1
17
  ## 0.0.2 (2025-07-22)
2
18
 
3
19
  ### 🩹 Fixes
package/build/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BaseStorageOptions, SchemaTypeRecord, BaseStorage, Doc, Operation, QueryType, QueryOptions } from '@trust0/ridb-core';
1
+ import { BaseStorageOptions, SchemaTypeRecord, BaseStorage } from '@trust0/ridb-core';
2
2
 
3
3
  /**
4
4
  * @packageDocumentation
@@ -32,49 +32,6 @@ interface MongoDBConfig {
32
32
  mongoOptions?: Record<string, any>;
33
33
  }
34
34
  type MongoDBStorageOptions = BaseStorageOptions & MongoDBConfig;
35
- /**
36
- * MongoDB storage implementation class
37
- * @public
38
- */
39
- declare class MongoDBStorage<T extends SchemaTypeRecord> extends BaseStorage<T> {
40
- private client?;
41
- private db?;
42
- private mongoConfig;
43
- constructor(name: string, schemas: T, options?: MongoDBStorageOptions);
44
- /**
45
- * Utility method to recursively convert ObjectId values to strings throughout an object
46
- * This ensures that MongoDB's ObjectId instances are never returned to the application layer,
47
- * maintaining consistency with RIDB's string-based approach and preventing serialization issues.
48
- * Also removes MongoDB's automatic _id field entirely from results.
49
- * @private
50
- */
51
- private convertObjectIdsToStrings;
52
- /**
53
- * Create a new MongoDB storage instance
54
- * @param name - Database name
55
- * @param schemas - Collection schemas
56
- * @param options - Storage options including MongoDB connection details
57
- * @returns A new Instance of MongoDB storage
58
- * @public
59
- */
60
- static create<SchemasCreate extends SchemaTypeRecord>(name: string, schemas: SchemasCreate, options?: MongoDBStorageOptions): Promise<MongoDBStorage<SchemasCreate>>;
61
- /** Start the database connection */
62
- start(): Promise<void>;
63
- /** Close the database connection */
64
- close(): Promise<void>;
65
- /** Get MongoDB collection for a given collection name */
66
- private getCollection;
67
- /** Find a document by its ID */
68
- findDocumentById(collectionName: keyof T, id: string): Promise<Doc<T[keyof T]> | null>;
69
- /** Write an operation (insert, update, delete) */
70
- write(op: Operation<T[keyof T]>): Promise<Doc<T[keyof T]>>;
71
- /** Convert RIDB query to MongoDB filter */
72
- private convertQueryToMongoFilter;
73
- /** Count documents matching a query (supports offset & limit) */
74
- count(collectionName: keyof T, query: QueryType<T[keyof T]>, options?: QueryOptions): Promise<number>;
75
- /** Find documents matching a query with pagination */
76
- find(collectionName: keyof T, query: QueryType<T[keyof T]>, options?: QueryOptions): Promise<Doc<T[keyof T]>[]>;
77
- }
78
35
  /**
79
36
  * Create a MongoDB storage instance
80
37
  * @public
@@ -82,4 +39,4 @@ declare class MongoDBStorage<T extends SchemaTypeRecord> extends BaseStorage<T>
82
39
  */
83
40
  declare function createMongoDB<T extends SchemaTypeRecord>(): Promise<typeof BaseStorage<T>>;
84
41
 
85
- export { type MongoDBConfig, MongoDBStorage, type MongoDBStorageOptions, createMongoDB };
42
+ export { type MongoDBConfig, type MongoDBStorageOptions, createMongoDB };
package/build/index.js CHANGED
@@ -76,7 +76,7 @@ var require_ridb_core = __commonJS({
76
76
  var ridb_core_exports = {};
77
77
  __export2(ridb_core_exports, {
78
78
  BasePlugin: () => BasePlugin,
79
- BaseStorage: () => BaseStorage2,
79
+ BaseStorage: () => BaseStorage,
80
80
  Collection: () => Collection,
81
81
  CoreStorage: () => CoreStorage,
82
82
  Database: () => Database,
@@ -431,6 +431,7 @@ ${val.stack}`;
431
431
  function __wbg_adapter_392(arg0, arg1, arg2, arg3) {
432
432
  wasm.wasm_bindgen__convert__closures__invoke2_mut__hdfe55fa2a247d1ac(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
433
433
  }
434
+ var Errors = Object.freeze({ Error: 0, "0": "Error", HookError: 1, "1": "HookError", QueryError: 2, "2": "QueryError", SerializationError: 3, "3": "SerializationError", ValidationError: 4, "4": "ValidationError", AuthenticationError: 5, "5": "AuthenticationError" });
434
435
  var OpType2 = Object.freeze({
435
436
  /**
436
437
  * Create operation.
@@ -458,7 +459,6 @@ ${val.stack}`;
458
459
  COUNT: 4,
459
460
  "4": "COUNT"
460
461
  });
461
- var Errors = Object.freeze({ Error: 0, "0": "Error", HookError: 1, "1": "HookError", QueryError: 2, "2": "QueryError", SerializationError: 3, "3": "SerializationError", ValidationError: 4, "4": "ValidationError", AuthenticationError: 5, "5": "AuthenticationError" });
462
462
  var BasePluginFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
463
463
  }, unregister: () => {
464
464
  } } : new FinalizationRegistry((ptr) => wasm.__wbg_baseplugin_free(ptr >>> 0));
@@ -531,7 +531,7 @@ ${val.stack}`;
531
531
  var BaseStorageFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
532
532
  }, unregister: () => {
533
533
  } } : new FinalizationRegistry((ptr) => wasm.__wbg_basestorage_free(ptr >>> 0));
534
- var BaseStorage2 = class {
534
+ var BaseStorage = class {
535
535
  __destroy_into_raw() {
536
536
  const ptr = this.__wbg_ptr;
537
537
  this.__wbg_ptr = 0;
@@ -3150,220 +3150,228 @@ ${val.stack}`;
3150
3150
  // src/index.ts
3151
3151
  var index_exports = {};
3152
3152
  __export(index_exports, {
3153
- MongoDBStorage: () => MongoDBStorage,
3154
3153
  createMongoDB: () => createMongoDB
3155
3154
  });
3156
3155
  module.exports = __toCommonJS(index_exports);
3157
3156
  var import_ridb_core = __toESM(require_ridb_core());
3158
3157
  var import_ridb = require("@trust0/ridb");
3159
- var MongoDBStorage = class _MongoDBStorage extends import_ridb_core.BaseStorage {
3160
- client;
3161
- db;
3162
- mongoConfig;
3163
- constructor(name, schemas, options = {}) {
3164
- super(name, schemas, options);
3165
- this.mongoConfig = options;
3166
- }
3167
- /**
3168
- * Utility method to recursively convert ObjectId values to strings throughout an object
3169
- * This ensures that MongoDB's ObjectId instances are never returned to the application layer,
3170
- * maintaining consistency with RIDB's string-based approach and preventing serialization issues.
3171
- * Also removes MongoDB's automatic _id field entirely from results.
3172
- * @private
3173
- */
3174
- convertObjectIdsToStrings(obj) {
3175
- if (!obj || typeof obj !== "object") {
3176
- return obj;
3177
- }
3178
- if (obj.constructor?.name === "ObjectId" || obj._bsontype && obj._bsontype === "ObjectId") {
3179
- const stringValue = obj.toString();
3180
- return stringValue;
3181
- }
3182
- if (Array.isArray(obj)) {
3183
- return obj.map((item) => this.convertObjectIdsToStrings(item));
3158
+ async function createMongoDB() {
3159
+ const { BaseStorage } = await (0, import_ridb.WasmInternal)();
3160
+ class MongoDBStorage extends BaseStorage {
3161
+ client;
3162
+ db;
3163
+ mongoConfig;
3164
+ constructor(name, schemas, options = {}) {
3165
+ super(name, schemas, options);
3166
+ this.mongoConfig = options;
3184
3167
  }
3185
- const converted = {};
3186
- for (const [key, value] of Object.entries(obj)) {
3187
- if (key === "_id") {
3188
- continue;
3168
+ /**
3169
+ * Utility method to recursively convert ObjectId values to strings throughout an object
3170
+ * This ensures that MongoDB's ObjectId instances are never returned to the application layer,
3171
+ * maintaining consistency with RIDB's string-based approach and preventing serialization issues.
3172
+ * Also removes MongoDB's automatic _id field entirely from results.
3173
+ * @private
3174
+ */
3175
+ convertObjectIdsToStrings(obj) {
3176
+ if (!obj || typeof obj !== "object") {
3177
+ return obj;
3178
+ }
3179
+ if (obj.constructor?.name === "ObjectId" || obj._bsontype && obj._bsontype === "ObjectId") {
3180
+ const stringValue = obj.toString();
3181
+ return stringValue;
3189
3182
  }
3190
- converted[key] = this.convertObjectIdsToStrings(value);
3183
+ if (Array.isArray(obj)) {
3184
+ return obj.map((item) => this.convertObjectIdsToStrings(item));
3185
+ }
3186
+ const converted = {};
3187
+ for (const [key, value] of Object.entries(obj)) {
3188
+ if (key === "_id") {
3189
+ continue;
3190
+ }
3191
+ converted[key] = this.convertObjectIdsToStrings(value);
3192
+ }
3193
+ return converted;
3191
3194
  }
3192
- return converted;
3193
- }
3194
- /**
3195
- * Create a new MongoDB storage instance
3196
- * @param name - Database name
3197
- * @param schemas - Collection schemas
3198
- * @param options - Storage options including MongoDB connection details
3199
- * @returns A new Instance of MongoDB storage
3200
- * @public
3201
- */
3202
- static async create(name, schemas, options = {}) {
3203
- const db = new _MongoDBStorage(name, schemas, options);
3204
- return db;
3205
- }
3206
- /** Start the database connection */
3207
- async start() {
3208
- const { MongoClient } = await import("mongodb");
3209
- const url = this.mongoConfig.url || process.env.MONGODB_URL || "mongodb://localhost:27017";
3210
- const dbName = this.mongoConfig.dbName || this.name;
3211
- this.client = new MongoClient(url, this.mongoConfig.mongoOptions || {});
3212
- await this.client.connect();
3213
- this.db = this.client.db(dbName);
3214
- }
3215
- /** Close the database connection */
3216
- async close() {
3217
- if (this.client) {
3218
- await this.client.close();
3219
- this.client = void 0;
3220
- this.db = void 0;
3195
+ /**
3196
+ * Create a new MongoDB storage instance
3197
+ * @param name - Database name
3198
+ * @param schemas - Collection schemas
3199
+ * @param options - Storage options including MongoDB connection details
3200
+ * @returns A new Instance of MongoDB storage
3201
+ * @public
3202
+ */
3203
+ static async create(name, schemas, options = {}) {
3204
+ const db = new MongoDBStorage(name, schemas, options);
3205
+ return db;
3221
3206
  }
3222
- }
3223
- /** Get MongoDB collection for a given collection name */
3224
- getCollection(collectionName) {
3225
- if (!this.db) {
3226
- throw new Error("Database not started. Call start() first.");
3207
+ /** Start the database connection */
3208
+ async start() {
3209
+ const { MongoClient } = await import("mongodb");
3210
+ const url = this.mongoConfig.url || process.env.MONGODB_URL;
3211
+ if (!url) {
3212
+ throw new Error("MONGODB_URL is required");
3213
+ }
3214
+ const dbName = this.mongoConfig.dbName || this.name;
3215
+ this.client = new MongoClient(url, {
3216
+ connectTimeoutMS: 5e3,
3217
+ serverSelectionTimeoutMS: 5e3,
3218
+ socketTimeoutMS: 5e3,
3219
+ maxPoolSize: 10,
3220
+ minPoolSize: 5,
3221
+ maxIdleTimeMS: 5e3,
3222
+ maxConnecting: 5
3223
+ });
3224
+ await this.client.connect();
3225
+ this.db = this.client.db(dbName);
3227
3226
  }
3228
- const collection = this.db.collection(collectionName);
3229
- return collection;
3230
- }
3231
- /** Find a document by its ID */
3232
- async findDocumentById(collectionName, id) {
3233
- const collection = this.getCollection(String(collectionName));
3234
- const schema = this.getSchema(String(collectionName));
3235
- const primaryKey = schema.primaryKey;
3236
- const query = { [primaryKey]: id };
3237
- const doc = await collection.findOne(query);
3238
- if (!doc) {
3239
- return null;
3227
+ /** Close the database connection */
3228
+ async close() {
3229
+ if (this.client) {
3230
+ await this.client.close();
3231
+ this.client = void 0;
3232
+ this.db = void 0;
3233
+ }
3240
3234
  }
3241
- const converted = this.convertObjectIdsToStrings(doc);
3242
- return converted;
3243
- }
3244
- /** Write an operation (insert, update, delete) */
3245
- async write(op) {
3246
- const collectionName = String(op.collection);
3247
- const collection = this.getCollection(collectionName);
3248
- const { primaryKey } = this.getSchema(collectionName);
3249
- switch (op.opType) {
3250
- case import_ridb_core.OpType.CREATE: {
3251
- const id = primaryKey in op.data ? op.data[primaryKey] : null;
3252
- if (!id) {
3253
- throw new Error("Document ID is required");
3254
- }
3255
- const existQuery = { [primaryKey]: id };
3256
- const existing = await collection.findOne(existQuery);
3257
- if (existing) {
3258
- throw new Error(`Document with ${primaryKey} '${id}' already exists`);
3259
- }
3260
- const docToInsert = { ...op.data };
3261
- const insertResult = await collection.insertOne(docToInsert);
3262
- const result = this.convertObjectIdsToStrings(op.data);
3263
- return result;
3264
- }
3265
- case import_ridb_core.OpType.UPDATE: {
3266
- const id = primaryKey in op.data ? op.data[primaryKey] : null;
3267
- if (!id) {
3268
- throw new Error("Document ID is required");
3269
- }
3270
- const updateQuery = { [primaryKey]: id };
3271
- const updateData = { $set: op.data };
3272
- const result = await collection.updateOne(updateQuery, updateData);
3273
- if (result.matchedCount === 0) {
3274
- throw new Error("Document ID not found");
3275
- }
3276
- const convertedResult = this.convertObjectIdsToStrings(op.data);
3277
- return convertedResult;
3278
- }
3279
- case import_ridb_core.OpType.DELETE: {
3280
- const id = op.data;
3281
- const deleteQuery = { [primaryKey]: id };
3282
- const result = await collection.deleteOne(deleteQuery);
3283
- if (result.deletedCount === 0) {
3284
- throw new Error("Document ID not found");
3285
- }
3286
- const convertedResult = this.convertObjectIdsToStrings(op.data);
3287
- return convertedResult;
3288
- }
3289
- default:
3290
- throw new Error(`Unknown operation type: ${op.opType}`);
3235
+ /** Get MongoDB collection for a given collection name */
3236
+ getCollection(collectionName) {
3237
+ if (!this.db) {
3238
+ throw new Error("Database not started. Call start() first.");
3239
+ }
3240
+ const collection = this.db.collection(collectionName);
3241
+ return collection;
3291
3242
  }
3292
- }
3293
- /** Convert RIDB query to MongoDB filter */
3294
- convertQueryToMongoFilter(query, schema) {
3295
- if (!query || typeof query !== "object") {
3296
- return {};
3243
+ /** Find a document by its ID */
3244
+ async findDocumentById(collectionName, id) {
3245
+ const collection = this.getCollection(String(collectionName));
3246
+ const schema = this.getSchema(String(collectionName));
3247
+ const primaryKey = schema.primaryKey;
3248
+ const query = { [primaryKey]: id };
3249
+ const doc = await collection.findOne(query);
3250
+ if (!doc) {
3251
+ return null;
3252
+ }
3253
+ const converted = this.convertObjectIdsToStrings(doc);
3254
+ return converted;
3255
+ }
3256
+ /** Write an operation (insert, update, delete) */
3257
+ async write(op) {
3258
+ const collectionName = String(op.collection);
3259
+ const collection = this.getCollection(collectionName);
3260
+ const { primaryKey } = this.getSchema(collectionName);
3261
+ switch (op.opType) {
3262
+ case import_ridb_core.OpType.CREATE: {
3263
+ const id = primaryKey in op.data ? op.data[primaryKey] : null;
3264
+ if (!id) {
3265
+ throw new Error("Document ID is required");
3266
+ }
3267
+ const existQuery = { [primaryKey]: id };
3268
+ const existing = await collection.findOne(existQuery);
3269
+ if (existing) {
3270
+ throw new Error(`Document with ${primaryKey} '${id}' already exists`);
3271
+ }
3272
+ const docToInsert = { ...op.data };
3273
+ const insertResult = await collection.insertOne(docToInsert);
3274
+ const result = this.convertObjectIdsToStrings(op.data);
3275
+ return result;
3276
+ }
3277
+ case import_ridb_core.OpType.UPDATE: {
3278
+ const id = primaryKey in op.data ? op.data[primaryKey] : null;
3279
+ if (!id) {
3280
+ throw new Error("Document ID is required");
3281
+ }
3282
+ const updateQuery = { [primaryKey]: id };
3283
+ const updateData = { $set: op.data };
3284
+ const result = await collection.updateOne(updateQuery, updateData);
3285
+ if (result.matchedCount === 0) {
3286
+ throw new Error("Document ID not found");
3287
+ }
3288
+ const convertedResult = this.convertObjectIdsToStrings(op.data);
3289
+ return convertedResult;
3290
+ }
3291
+ case import_ridb_core.OpType.DELETE: {
3292
+ const id = op.data;
3293
+ const deleteQuery = { [primaryKey]: id };
3294
+ const result = await collection.deleteOne(deleteQuery);
3295
+ if (result.deletedCount === 0) {
3296
+ throw new Error("Document ID not found");
3297
+ }
3298
+ const convertedResult = this.convertObjectIdsToStrings(op.data);
3299
+ return convertedResult;
3300
+ }
3301
+ default:
3302
+ throw new Error(`Unknown operation type: ${op.opType}`);
3303
+ }
3297
3304
  }
3298
- const filter = {};
3299
- for (const [key, value] of Object.entries(query)) {
3300
- if (value === null || value === void 0) {
3301
- filter[key] = { $exists: false };
3302
- } else if (typeof value === "object" && value !== null) {
3303
- if ("$in" in value) {
3304
- filter[key] = { $in: this.convertObjectIdsToStrings(value.$in) };
3305
- } else if ("$nin" in value) {
3306
- filter[key] = { $nin: this.convertObjectIdsToStrings(value.$nin) };
3307
- } else if ("$gt" in value) {
3308
- filter[key] = { $gt: this.convertObjectIdsToStrings(value.$gt) };
3309
- } else if ("$gte" in value) {
3310
- filter[key] = { $gte: this.convertObjectIdsToStrings(value.$gte) };
3311
- } else if ("$lt" in value) {
3312
- filter[key] = { $lt: this.convertObjectIdsToStrings(value.$lt) };
3313
- } else if ("$lte" in value) {
3314
- filter[key] = { $lte: this.convertObjectIdsToStrings(value.$lte) };
3315
- } else if ("$ne" in value) {
3316
- filter[key] = { $ne: this.convertObjectIdsToStrings(value.$ne) };
3317
- } else if ("$regex" in value) {
3318
- filter[key] = { $regex: value.$regex };
3305
+ /** Convert RIDB query to MongoDB filter */
3306
+ convertQueryToMongoFilter(query, schema) {
3307
+ if (!query || typeof query !== "object") {
3308
+ return {};
3309
+ }
3310
+ const filter = {};
3311
+ for (const [key, value] of Object.entries(query)) {
3312
+ if (value === null || value === void 0) {
3313
+ filter[key] = { $exists: false };
3314
+ } else if (typeof value === "object" && value !== null) {
3315
+ if ("$in" in value) {
3316
+ filter[key] = { $in: this.convertObjectIdsToStrings(value.$in) };
3317
+ } else if ("$nin" in value) {
3318
+ filter[key] = { $nin: this.convertObjectIdsToStrings(value.$nin) };
3319
+ } else if ("$gt" in value) {
3320
+ filter[key] = { $gt: this.convertObjectIdsToStrings(value.$gt) };
3321
+ } else if ("$gte" in value) {
3322
+ filter[key] = { $gte: this.convertObjectIdsToStrings(value.$gte) };
3323
+ } else if ("$lt" in value) {
3324
+ filter[key] = { $lt: this.convertObjectIdsToStrings(value.$lt) };
3325
+ } else if ("$lte" in value) {
3326
+ filter[key] = { $lte: this.convertObjectIdsToStrings(value.$lte) };
3327
+ } else if ("$ne" in value) {
3328
+ filter[key] = { $ne: this.convertObjectIdsToStrings(value.$ne) };
3329
+ } else if ("$regex" in value) {
3330
+ filter[key] = { $regex: value.$regex };
3331
+ } else {
3332
+ filter[key] = this.convertObjectIdsToStrings(value);
3333
+ }
3319
3334
  } else {
3320
3335
  filter[key] = this.convertObjectIdsToStrings(value);
3321
3336
  }
3322
- } else {
3323
- filter[key] = this.convertObjectIdsToStrings(value);
3324
3337
  }
3338
+ return filter;
3325
3339
  }
3326
- return filter;
3327
- }
3328
- /** Count documents matching a query (supports offset & limit) */
3329
- async count(collectionName, query, options) {
3330
- const collection = this.getCollection(String(collectionName));
3331
- const schema = this.getSchema(String(collectionName));
3332
- const filter = this.convertQueryToMongoFilter(query, schema);
3333
- let countOptions = {};
3334
- if (options?.offset) {
3335
- countOptions.skip = options.offset;
3340
+ /** Count documents matching a query (supports offset & limit) */
3341
+ async count(collectionName, query, options) {
3342
+ const collection = this.getCollection(String(collectionName));
3343
+ const schema = this.getSchema(String(collectionName));
3344
+ const filter = this.convertQueryToMongoFilter(query, schema);
3345
+ let countOptions = {};
3346
+ if (options?.offset) {
3347
+ countOptions.skip = options.offset;
3348
+ }
3349
+ if (options?.limit) {
3350
+ countOptions.limit = options.limit;
3351
+ }
3352
+ const count = await collection.countDocuments(filter, Object.keys(countOptions).length > 0 ? countOptions : void 0);
3353
+ return count;
3336
3354
  }
3337
- if (options?.limit) {
3338
- countOptions.limit = options.limit;
3355
+ /** Find documents matching a query with pagination */
3356
+ async find(collectionName, query, options) {
3357
+ const collection = this.getCollection(String(collectionName));
3358
+ const schema = this.getSchema(String(collectionName));
3359
+ const filter = this.convertQueryToMongoFilter(query, schema);
3360
+ let findQuery = collection.find(filter);
3361
+ if (options?.offset) {
3362
+ findQuery = findQuery.skip(options.offset);
3363
+ }
3364
+ if (options?.limit) {
3365
+ findQuery = findQuery.limit(options.limit);
3366
+ }
3367
+ const docs = await findQuery.toArray();
3368
+ const convertedDocs = docs.map((doc) => this.convertObjectIdsToStrings(doc));
3369
+ return convertedDocs;
3339
3370
  }
3340
- const count = await collection.countDocuments(filter, Object.keys(countOptions).length > 0 ? countOptions : void 0);
3341
- return count;
3342
3371
  }
3343
- /** Find documents matching a query with pagination */
3344
- async find(collectionName, query, options) {
3345
- const collection = this.getCollection(String(collectionName));
3346
- const schema = this.getSchema(String(collectionName));
3347
- const filter = this.convertQueryToMongoFilter(query, schema);
3348
- let findQuery = collection.find(filter);
3349
- if (options?.offset) {
3350
- findQuery = findQuery.skip(options.offset);
3351
- }
3352
- if (options?.limit) {
3353
- findQuery = findQuery.limit(options.limit);
3354
- }
3355
- const docs = await findQuery.toArray();
3356
- const convertedDocs = docs.map((doc) => this.convertObjectIdsToStrings(doc));
3357
- return convertedDocs;
3358
- }
3359
- };
3360
- async function createMongoDB() {
3361
- const { BaseStorage: base } = await (0, import_ridb.WasmInternal)();
3362
- Object.setPrototypeOf(MongoDBStorage.prototype, base.prototype);
3363
3372
  return MongoDBStorage;
3364
3373
  }
3365
3374
  // Annotate the CommonJS export names for ESM import in node:
3366
3375
  0 && (module.exports = {
3367
- MongoDBStorage,
3368
3376
  createMongoDB
3369
3377
  });
package/build/index.mjs CHANGED
@@ -70,7 +70,7 @@ var require_ridb_core = __commonJS({
70
70
  var ridb_core_exports = {};
71
71
  __export(ridb_core_exports, {
72
72
  BasePlugin: () => BasePlugin,
73
- BaseStorage: () => BaseStorage2,
73
+ BaseStorage: () => BaseStorage,
74
74
  Collection: () => Collection,
75
75
  CoreStorage: () => CoreStorage,
76
76
  Database: () => Database,
@@ -425,6 +425,7 @@ ${val.stack}`;
425
425
  function __wbg_adapter_392(arg0, arg1, arg2, arg3) {
426
426
  wasm.wasm_bindgen__convert__closures__invoke2_mut__hdfe55fa2a247d1ac(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
427
427
  }
428
+ var Errors = Object.freeze({ Error: 0, "0": "Error", HookError: 1, "1": "HookError", QueryError: 2, "2": "QueryError", SerializationError: 3, "3": "SerializationError", ValidationError: 4, "4": "ValidationError", AuthenticationError: 5, "5": "AuthenticationError" });
428
429
  var OpType2 = Object.freeze({
429
430
  /**
430
431
  * Create operation.
@@ -452,7 +453,6 @@ ${val.stack}`;
452
453
  COUNT: 4,
453
454
  "4": "COUNT"
454
455
  });
455
- var Errors = Object.freeze({ Error: 0, "0": "Error", HookError: 1, "1": "HookError", QueryError: 2, "2": "QueryError", SerializationError: 3, "3": "SerializationError", ValidationError: 4, "4": "ValidationError", AuthenticationError: 5, "5": "AuthenticationError" });
456
456
  var BasePluginFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
457
457
  }, unregister: () => {
458
458
  } } : new FinalizationRegistry((ptr) => wasm.__wbg_baseplugin_free(ptr >>> 0));
@@ -525,7 +525,7 @@ ${val.stack}`;
525
525
  var BaseStorageFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
526
526
  }, unregister: () => {
527
527
  } } : new FinalizationRegistry((ptr) => wasm.__wbg_basestorage_free(ptr >>> 0));
528
- var BaseStorage2 = class {
528
+ var BaseStorage = class {
529
529
  __destroy_into_raw() {
530
530
  const ptr = this.__wbg_ptr;
531
531
  this.__wbg_ptr = 0;
@@ -3146,213 +3146,222 @@ var import_ridb_core = __toESM(require_ridb_core());
3146
3146
  import {
3147
3147
  WasmInternal
3148
3148
  } from "@trust0/ridb";
3149
- var MongoDBStorage = class _MongoDBStorage extends import_ridb_core.BaseStorage {
3150
- client;
3151
- db;
3152
- mongoConfig;
3153
- constructor(name, schemas, options = {}) {
3154
- super(name, schemas, options);
3155
- this.mongoConfig = options;
3156
- }
3157
- /**
3158
- * Utility method to recursively convert ObjectId values to strings throughout an object
3159
- * This ensures that MongoDB's ObjectId instances are never returned to the application layer,
3160
- * maintaining consistency with RIDB's string-based approach and preventing serialization issues.
3161
- * Also removes MongoDB's automatic _id field entirely from results.
3162
- * @private
3163
- */
3164
- convertObjectIdsToStrings(obj) {
3165
- if (!obj || typeof obj !== "object") {
3166
- return obj;
3167
- }
3168
- if (obj.constructor?.name === "ObjectId" || obj._bsontype && obj._bsontype === "ObjectId") {
3169
- const stringValue = obj.toString();
3170
- return stringValue;
3171
- }
3172
- if (Array.isArray(obj)) {
3173
- return obj.map((item) => this.convertObjectIdsToStrings(item));
3149
+ async function createMongoDB() {
3150
+ const { BaseStorage } = await WasmInternal();
3151
+ class MongoDBStorage extends BaseStorage {
3152
+ client;
3153
+ db;
3154
+ mongoConfig;
3155
+ constructor(name, schemas, options = {}) {
3156
+ super(name, schemas, options);
3157
+ this.mongoConfig = options;
3174
3158
  }
3175
- const converted = {};
3176
- for (const [key, value] of Object.entries(obj)) {
3177
- if (key === "_id") {
3178
- continue;
3159
+ /**
3160
+ * Utility method to recursively convert ObjectId values to strings throughout an object
3161
+ * This ensures that MongoDB's ObjectId instances are never returned to the application layer,
3162
+ * maintaining consistency with RIDB's string-based approach and preventing serialization issues.
3163
+ * Also removes MongoDB's automatic _id field entirely from results.
3164
+ * @private
3165
+ */
3166
+ convertObjectIdsToStrings(obj) {
3167
+ if (!obj || typeof obj !== "object") {
3168
+ return obj;
3169
+ }
3170
+ if (obj.constructor?.name === "ObjectId" || obj._bsontype && obj._bsontype === "ObjectId") {
3171
+ const stringValue = obj.toString();
3172
+ return stringValue;
3179
3173
  }
3180
- converted[key] = this.convertObjectIdsToStrings(value);
3174
+ if (Array.isArray(obj)) {
3175
+ return obj.map((item) => this.convertObjectIdsToStrings(item));
3176
+ }
3177
+ const converted = {};
3178
+ for (const [key, value] of Object.entries(obj)) {
3179
+ if (key === "_id") {
3180
+ continue;
3181
+ }
3182
+ converted[key] = this.convertObjectIdsToStrings(value);
3183
+ }
3184
+ return converted;
3181
3185
  }
3182
- return converted;
3183
- }
3184
- /**
3185
- * Create a new MongoDB storage instance
3186
- * @param name - Database name
3187
- * @param schemas - Collection schemas
3188
- * @param options - Storage options including MongoDB connection details
3189
- * @returns A new Instance of MongoDB storage
3190
- * @public
3191
- */
3192
- static async create(name, schemas, options = {}) {
3193
- const db = new _MongoDBStorage(name, schemas, options);
3194
- return db;
3195
- }
3196
- /** Start the database connection */
3197
- async start() {
3198
- const { MongoClient } = await import("mongodb");
3199
- const url = this.mongoConfig.url || process.env.MONGODB_URL || "mongodb://localhost:27017";
3200
- const dbName = this.mongoConfig.dbName || this.name;
3201
- this.client = new MongoClient(url, this.mongoConfig.mongoOptions || {});
3202
- await this.client.connect();
3203
- this.db = this.client.db(dbName);
3204
- }
3205
- /** Close the database connection */
3206
- async close() {
3207
- if (this.client) {
3208
- await this.client.close();
3209
- this.client = void 0;
3210
- this.db = void 0;
3186
+ /**
3187
+ * Create a new MongoDB storage instance
3188
+ * @param name - Database name
3189
+ * @param schemas - Collection schemas
3190
+ * @param options - Storage options including MongoDB connection details
3191
+ * @returns A new Instance of MongoDB storage
3192
+ * @public
3193
+ */
3194
+ static async create(name, schemas, options = {}) {
3195
+ const db = new MongoDBStorage(name, schemas, options);
3196
+ return db;
3211
3197
  }
3212
- }
3213
- /** Get MongoDB collection for a given collection name */
3214
- getCollection(collectionName) {
3215
- if (!this.db) {
3216
- throw new Error("Database not started. Call start() first.");
3198
+ /** Start the database connection */
3199
+ async start() {
3200
+ const { MongoClient } = await import("mongodb");
3201
+ const url = this.mongoConfig.url || process.env.MONGODB_URL;
3202
+ if (!url) {
3203
+ throw new Error("MONGODB_URL is required");
3204
+ }
3205
+ const dbName = this.mongoConfig.dbName || this.name;
3206
+ this.client = new MongoClient(url, {
3207
+ connectTimeoutMS: 5e3,
3208
+ serverSelectionTimeoutMS: 5e3,
3209
+ socketTimeoutMS: 5e3,
3210
+ maxPoolSize: 10,
3211
+ minPoolSize: 5,
3212
+ maxIdleTimeMS: 5e3,
3213
+ maxConnecting: 5
3214
+ });
3215
+ await this.client.connect();
3216
+ this.db = this.client.db(dbName);
3217
3217
  }
3218
- const collection = this.db.collection(collectionName);
3219
- return collection;
3220
- }
3221
- /** Find a document by its ID */
3222
- async findDocumentById(collectionName, id) {
3223
- const collection = this.getCollection(String(collectionName));
3224
- const schema = this.getSchema(String(collectionName));
3225
- const primaryKey = schema.primaryKey;
3226
- const query = { [primaryKey]: id };
3227
- const doc = await collection.findOne(query);
3228
- if (!doc) {
3229
- return null;
3218
+ /** Close the database connection */
3219
+ async close() {
3220
+ if (this.client) {
3221
+ await this.client.close();
3222
+ this.client = void 0;
3223
+ this.db = void 0;
3224
+ }
3230
3225
  }
3231
- const converted = this.convertObjectIdsToStrings(doc);
3232
- return converted;
3233
- }
3234
- /** Write an operation (insert, update, delete) */
3235
- async write(op) {
3236
- const collectionName = String(op.collection);
3237
- const collection = this.getCollection(collectionName);
3238
- const { primaryKey } = this.getSchema(collectionName);
3239
- switch (op.opType) {
3240
- case import_ridb_core.OpType.CREATE: {
3241
- const id = primaryKey in op.data ? op.data[primaryKey] : null;
3242
- if (!id) {
3243
- throw new Error("Document ID is required");
3244
- }
3245
- const existQuery = { [primaryKey]: id };
3246
- const existing = await collection.findOne(existQuery);
3247
- if (existing) {
3248
- throw new Error(`Document with ${primaryKey} '${id}' already exists`);
3249
- }
3250
- const docToInsert = { ...op.data };
3251
- const insertResult = await collection.insertOne(docToInsert);
3252
- const result = this.convertObjectIdsToStrings(op.data);
3253
- return result;
3254
- }
3255
- case import_ridb_core.OpType.UPDATE: {
3256
- const id = primaryKey in op.data ? op.data[primaryKey] : null;
3257
- if (!id) {
3258
- throw new Error("Document ID is required");
3259
- }
3260
- const updateQuery = { [primaryKey]: id };
3261
- const updateData = { $set: op.data };
3262
- const result = await collection.updateOne(updateQuery, updateData);
3263
- if (result.matchedCount === 0) {
3264
- throw new Error("Document ID not found");
3265
- }
3266
- const convertedResult = this.convertObjectIdsToStrings(op.data);
3267
- return convertedResult;
3268
- }
3269
- case import_ridb_core.OpType.DELETE: {
3270
- const id = op.data;
3271
- const deleteQuery = { [primaryKey]: id };
3272
- const result = await collection.deleteOne(deleteQuery);
3273
- if (result.deletedCount === 0) {
3274
- throw new Error("Document ID not found");
3275
- }
3276
- const convertedResult = this.convertObjectIdsToStrings(op.data);
3277
- return convertedResult;
3278
- }
3279
- default:
3280
- throw new Error(`Unknown operation type: ${op.opType}`);
3226
+ /** Get MongoDB collection for a given collection name */
3227
+ getCollection(collectionName) {
3228
+ if (!this.db) {
3229
+ throw new Error("Database not started. Call start() first.");
3230
+ }
3231
+ const collection = this.db.collection(collectionName);
3232
+ return collection;
3281
3233
  }
3282
- }
3283
- /** Convert RIDB query to MongoDB filter */
3284
- convertQueryToMongoFilter(query, schema) {
3285
- if (!query || typeof query !== "object") {
3286
- return {};
3234
+ /** Find a document by its ID */
3235
+ async findDocumentById(collectionName, id) {
3236
+ const collection = this.getCollection(String(collectionName));
3237
+ const schema = this.getSchema(String(collectionName));
3238
+ const primaryKey = schema.primaryKey;
3239
+ const query = { [primaryKey]: id };
3240
+ const doc = await collection.findOne(query);
3241
+ if (!doc) {
3242
+ return null;
3243
+ }
3244
+ const converted = this.convertObjectIdsToStrings(doc);
3245
+ return converted;
3246
+ }
3247
+ /** Write an operation (insert, update, delete) */
3248
+ async write(op) {
3249
+ const collectionName = String(op.collection);
3250
+ const collection = this.getCollection(collectionName);
3251
+ const { primaryKey } = this.getSchema(collectionName);
3252
+ switch (op.opType) {
3253
+ case import_ridb_core.OpType.CREATE: {
3254
+ const id = primaryKey in op.data ? op.data[primaryKey] : null;
3255
+ if (!id) {
3256
+ throw new Error("Document ID is required");
3257
+ }
3258
+ const existQuery = { [primaryKey]: id };
3259
+ const existing = await collection.findOne(existQuery);
3260
+ if (existing) {
3261
+ throw new Error(`Document with ${primaryKey} '${id}' already exists`);
3262
+ }
3263
+ const docToInsert = { ...op.data };
3264
+ const insertResult = await collection.insertOne(docToInsert);
3265
+ const result = this.convertObjectIdsToStrings(op.data);
3266
+ return result;
3267
+ }
3268
+ case import_ridb_core.OpType.UPDATE: {
3269
+ const id = primaryKey in op.data ? op.data[primaryKey] : null;
3270
+ if (!id) {
3271
+ throw new Error("Document ID is required");
3272
+ }
3273
+ const updateQuery = { [primaryKey]: id };
3274
+ const updateData = { $set: op.data };
3275
+ const result = await collection.updateOne(updateQuery, updateData);
3276
+ if (result.matchedCount === 0) {
3277
+ throw new Error("Document ID not found");
3278
+ }
3279
+ const convertedResult = this.convertObjectIdsToStrings(op.data);
3280
+ return convertedResult;
3281
+ }
3282
+ case import_ridb_core.OpType.DELETE: {
3283
+ const id = op.data;
3284
+ const deleteQuery = { [primaryKey]: id };
3285
+ const result = await collection.deleteOne(deleteQuery);
3286
+ if (result.deletedCount === 0) {
3287
+ throw new Error("Document ID not found");
3288
+ }
3289
+ const convertedResult = this.convertObjectIdsToStrings(op.data);
3290
+ return convertedResult;
3291
+ }
3292
+ default:
3293
+ throw new Error(`Unknown operation type: ${op.opType}`);
3294
+ }
3287
3295
  }
3288
- const filter = {};
3289
- for (const [key, value] of Object.entries(query)) {
3290
- if (value === null || value === void 0) {
3291
- filter[key] = { $exists: false };
3292
- } else if (typeof value === "object" && value !== null) {
3293
- if ("$in" in value) {
3294
- filter[key] = { $in: this.convertObjectIdsToStrings(value.$in) };
3295
- } else if ("$nin" in value) {
3296
- filter[key] = { $nin: this.convertObjectIdsToStrings(value.$nin) };
3297
- } else if ("$gt" in value) {
3298
- filter[key] = { $gt: this.convertObjectIdsToStrings(value.$gt) };
3299
- } else if ("$gte" in value) {
3300
- filter[key] = { $gte: this.convertObjectIdsToStrings(value.$gte) };
3301
- } else if ("$lt" in value) {
3302
- filter[key] = { $lt: this.convertObjectIdsToStrings(value.$lt) };
3303
- } else if ("$lte" in value) {
3304
- filter[key] = { $lte: this.convertObjectIdsToStrings(value.$lte) };
3305
- } else if ("$ne" in value) {
3306
- filter[key] = { $ne: this.convertObjectIdsToStrings(value.$ne) };
3307
- } else if ("$regex" in value) {
3308
- filter[key] = { $regex: value.$regex };
3296
+ /** Convert RIDB query to MongoDB filter */
3297
+ convertQueryToMongoFilter(query, schema) {
3298
+ if (!query || typeof query !== "object") {
3299
+ return {};
3300
+ }
3301
+ const filter = {};
3302
+ for (const [key, value] of Object.entries(query)) {
3303
+ if (value === null || value === void 0) {
3304
+ filter[key] = { $exists: false };
3305
+ } else if (typeof value === "object" && value !== null) {
3306
+ if ("$in" in value) {
3307
+ filter[key] = { $in: this.convertObjectIdsToStrings(value.$in) };
3308
+ } else if ("$nin" in value) {
3309
+ filter[key] = { $nin: this.convertObjectIdsToStrings(value.$nin) };
3310
+ } else if ("$gt" in value) {
3311
+ filter[key] = { $gt: this.convertObjectIdsToStrings(value.$gt) };
3312
+ } else if ("$gte" in value) {
3313
+ filter[key] = { $gte: this.convertObjectIdsToStrings(value.$gte) };
3314
+ } else if ("$lt" in value) {
3315
+ filter[key] = { $lt: this.convertObjectIdsToStrings(value.$lt) };
3316
+ } else if ("$lte" in value) {
3317
+ filter[key] = { $lte: this.convertObjectIdsToStrings(value.$lte) };
3318
+ } else if ("$ne" in value) {
3319
+ filter[key] = { $ne: this.convertObjectIdsToStrings(value.$ne) };
3320
+ } else if ("$regex" in value) {
3321
+ filter[key] = { $regex: value.$regex };
3322
+ } else {
3323
+ filter[key] = this.convertObjectIdsToStrings(value);
3324
+ }
3309
3325
  } else {
3310
3326
  filter[key] = this.convertObjectIdsToStrings(value);
3311
3327
  }
3312
- } else {
3313
- filter[key] = this.convertObjectIdsToStrings(value);
3314
3328
  }
3329
+ return filter;
3315
3330
  }
3316
- return filter;
3317
- }
3318
- /** Count documents matching a query (supports offset & limit) */
3319
- async count(collectionName, query, options) {
3320
- const collection = this.getCollection(String(collectionName));
3321
- const schema = this.getSchema(String(collectionName));
3322
- const filter = this.convertQueryToMongoFilter(query, schema);
3323
- let countOptions = {};
3324
- if (options?.offset) {
3325
- countOptions.skip = options.offset;
3331
+ /** Count documents matching a query (supports offset & limit) */
3332
+ async count(collectionName, query, options) {
3333
+ const collection = this.getCollection(String(collectionName));
3334
+ const schema = this.getSchema(String(collectionName));
3335
+ const filter = this.convertQueryToMongoFilter(query, schema);
3336
+ let countOptions = {};
3337
+ if (options?.offset) {
3338
+ countOptions.skip = options.offset;
3339
+ }
3340
+ if (options?.limit) {
3341
+ countOptions.limit = options.limit;
3342
+ }
3343
+ const count = await collection.countDocuments(filter, Object.keys(countOptions).length > 0 ? countOptions : void 0);
3344
+ return count;
3326
3345
  }
3327
- if (options?.limit) {
3328
- countOptions.limit = options.limit;
3346
+ /** Find documents matching a query with pagination */
3347
+ async find(collectionName, query, options) {
3348
+ const collection = this.getCollection(String(collectionName));
3349
+ const schema = this.getSchema(String(collectionName));
3350
+ const filter = this.convertQueryToMongoFilter(query, schema);
3351
+ let findQuery = collection.find(filter);
3352
+ if (options?.offset) {
3353
+ findQuery = findQuery.skip(options.offset);
3354
+ }
3355
+ if (options?.limit) {
3356
+ findQuery = findQuery.limit(options.limit);
3357
+ }
3358
+ const docs = await findQuery.toArray();
3359
+ const convertedDocs = docs.map((doc) => this.convertObjectIdsToStrings(doc));
3360
+ return convertedDocs;
3329
3361
  }
3330
- const count = await collection.countDocuments(filter, Object.keys(countOptions).length > 0 ? countOptions : void 0);
3331
- return count;
3332
3362
  }
3333
- /** Find documents matching a query with pagination */
3334
- async find(collectionName, query, options) {
3335
- const collection = this.getCollection(String(collectionName));
3336
- const schema = this.getSchema(String(collectionName));
3337
- const filter = this.convertQueryToMongoFilter(query, schema);
3338
- let findQuery = collection.find(filter);
3339
- if (options?.offset) {
3340
- findQuery = findQuery.skip(options.offset);
3341
- }
3342
- if (options?.limit) {
3343
- findQuery = findQuery.limit(options.limit);
3344
- }
3345
- const docs = await findQuery.toArray();
3346
- const convertedDocs = docs.map((doc) => this.convertObjectIdsToStrings(doc));
3347
- return convertedDocs;
3348
- }
3349
- };
3350
- async function createMongoDB() {
3351
- const { BaseStorage: base } = await WasmInternal();
3352
- Object.setPrototypeOf(MongoDBStorage.prototype, base.prototype);
3353
3363
  return MongoDBStorage;
3354
3364
  }
3355
3365
  export {
3356
- MongoDBStorage,
3357
3366
  createMongoDB
3358
3367
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@trust0/ridb-mongodb",
3
- "version": "0.0.2",
4
- "description": "MongoDB storage for @trust0/ridb.",
3
+ "version": "0.0.3",
4
+ "description": "MongoDB storage for @trust0/ridb",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",
7
7
  "types": "./build/index.d.ts",
@@ -31,7 +31,7 @@
31
31
  "types:default": "npx tsc"
32
32
  },
33
33
  "devDependencies": {
34
- "@trust0/ridb": "^1.5.35",
34
+ "@trust0/ridb": "^1.5.36",
35
35
  "@trust0/ridb-build": "^0.0.16",
36
36
  "jsdom": "^24.1.3",
37
37
  "mongodb": "^6.0.0",