@orion-js/mongodb 4.2.0 → 4.2.1

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/dist/index.d.cts CHANGED
@@ -304,6 +304,58 @@ declare function createCollection<T extends TypedSchemaOnSchema & {
304
304
  }>(options: CreateCollectionOptionsWithTypedSchema<T>): Collection<InferSchemaType<T>>;
305
305
  declare function createCollection<T extends ModelClassBase>(options: CreateCollectionOptions<T>): Collection<T>;
306
306
 
307
+ /**
308
+ * Result of the deleteUnusedIndexes operation
309
+ */
310
+ interface DeleteUnusedIndexesResult {
311
+ /** Names of the indexes that were deleted */
312
+ deletedIndexes: string[];
313
+ /** Name of the collection that was cleaned */
314
+ collectionName: string;
315
+ }
316
+
317
+ /**
318
+ * Registry that tracks all collections created via createCollection().
319
+ * Maps connection name to a map of collection name to collection instance.
320
+ */
321
+ declare const collectionsRegistry: Map<string, Map<string, Collection<ModelClassBase>>>;
322
+ /**
323
+ * Registers a collection in the registry.
324
+ * Called automatically when a collection is created via createCollection().
325
+ * @param connectionName - The name of the MongoDB connection
326
+ * @param collection - The collection instance to register
327
+ */
328
+ declare function registerCollection(connectionName: string, collection: Collection<ModelClassBase>): void;
329
+ /**
330
+ * Gets all registered collections for a specific connection.
331
+ * @param connectionName - The name of the MongoDB connection (defaults to 'main')
332
+ * @returns Array of registered collections for the connection
333
+ */
334
+ declare function getRegisteredCollections(connectionName?: string): Array<Collection<ModelClassBase>>;
335
+ /**
336
+ * Deletes unused indexes from all registered collections for a connection.
337
+ * Iterates over all collections registered via createCollection() and
338
+ * removes indexes that exist in MongoDB but are not defined in the collection configuration.
339
+ *
340
+ * @param connectionName - The name of the MongoDB connection (defaults to 'main')
341
+ * @returns Array of results for each collection that had indexes deleted
342
+ *
343
+ * @example
344
+ * ```ts
345
+ * // Delete unused indexes from all collections on the main connection
346
+ * const results = await deleteAllUnusedIndexes()
347
+ *
348
+ * // Delete unused indexes from all collections on a specific connection
349
+ * const results = await deleteAllUnusedIndexes('secondary')
350
+ *
351
+ * // Log results
352
+ * for (const result of results) {
353
+ * console.log(`${result.collectionName}: deleted ${result.deletedIndexes.length} indexes`)
354
+ * }
355
+ * ```
356
+ */
357
+ declare function deleteAllUnusedIndexes(connectionName?: string): Promise<DeleteUnusedIndexesResult[]>;
358
+
307
359
  declare function getOrCreateEncryptionKey({ keyAltName, kmsProvider, masterKey, connectionName, keyVaultDatabase, keyVaultCollection, kmsProviders, }: {
308
360
  keyAltName: string;
309
361
  kmsProvider: keyof KMSProviders;
@@ -321,4 +373,4 @@ declare const ENCRYPTION_ALGORITHMS: {
321
373
  RANDOM: string;
322
374
  };
323
375
 
324
- export { BaseCollection, Collection, type CollectionIndex, type CountDocuments, type CreateCollectionOptions, type CreateCollectionOptionsWithSchemaType, type CreateCollectionOptionsWithTypedSchema, DataLoader, type DeleteMany, type DeleteOne, type DistinctDocumentId, type DocumentWithId, ENCRYPTION_ALGORITHMS, type EstimatedDocumentCount, type Find, type FindCursor, type FindOne, type FindOneAndUpdate, type FindOneAndUpdateUpdateOptions, type InferIdType, type InferSchemaTypeWithId, type InitItem, type InsertAndFind, type InsertMany, type InsertManyOptions, type InsertOne, type InsertOptions, type ModelClassBase, type ModelToMongoSelector, MongoCollection, type MongoFilter, type MongoSelector, type OptionalId, Repository, type SchemaWithRequiredId, type TypedId, type UpdateAndFind, type UpdateItem, type UpdateMany, type UpdateOne, type UpdateOptions, type Upsert, allConnectionPromises, configureConnection, connections, createCollection, createIndexesPromises, getDBName, getMongoConnection, getOrCreateEncryptionKey, typedId };
376
+ export { BaseCollection, Collection, type CollectionIndex, type CountDocuments, type CreateCollectionOptions, type CreateCollectionOptionsWithSchemaType, type CreateCollectionOptionsWithTypedSchema, DataLoader, type DeleteMany, type DeleteOne, type DistinctDocumentId, type DocumentWithId, ENCRYPTION_ALGORITHMS, type EstimatedDocumentCount, type Find, type FindCursor, type FindOne, type FindOneAndUpdate, type FindOneAndUpdateUpdateOptions, type InferIdType, type InferSchemaTypeWithId, type InitItem, type InsertAndFind, type InsertMany, type InsertManyOptions, type InsertOne, type InsertOptions, type ModelClassBase, type ModelToMongoSelector, MongoCollection, type MongoFilter, type MongoSelector, type OptionalId, Repository, type SchemaWithRequiredId, type TypedId, type UpdateAndFind, type UpdateItem, type UpdateMany, type UpdateOne, type UpdateOptions, type Upsert, allConnectionPromises, collectionsRegistry, configureConnection, connections, createCollection, createIndexesPromises, deleteAllUnusedIndexes, getDBName, getMongoConnection, getOrCreateEncryptionKey, getRegisteredCollections, registerCollection, typedId };
package/dist/index.d.ts CHANGED
@@ -304,6 +304,58 @@ declare function createCollection<T extends TypedSchemaOnSchema & {
304
304
  }>(options: CreateCollectionOptionsWithTypedSchema<T>): Collection<InferSchemaType<T>>;
305
305
  declare function createCollection<T extends ModelClassBase>(options: CreateCollectionOptions<T>): Collection<T>;
306
306
 
307
+ /**
308
+ * Result of the deleteUnusedIndexes operation
309
+ */
310
+ interface DeleteUnusedIndexesResult {
311
+ /** Names of the indexes that were deleted */
312
+ deletedIndexes: string[];
313
+ /** Name of the collection that was cleaned */
314
+ collectionName: string;
315
+ }
316
+
317
+ /**
318
+ * Registry that tracks all collections created via createCollection().
319
+ * Maps connection name to a map of collection name to collection instance.
320
+ */
321
+ declare const collectionsRegistry: Map<string, Map<string, Collection<ModelClassBase>>>;
322
+ /**
323
+ * Registers a collection in the registry.
324
+ * Called automatically when a collection is created via createCollection().
325
+ * @param connectionName - The name of the MongoDB connection
326
+ * @param collection - The collection instance to register
327
+ */
328
+ declare function registerCollection(connectionName: string, collection: Collection<ModelClassBase>): void;
329
+ /**
330
+ * Gets all registered collections for a specific connection.
331
+ * @param connectionName - The name of the MongoDB connection (defaults to 'main')
332
+ * @returns Array of registered collections for the connection
333
+ */
334
+ declare function getRegisteredCollections(connectionName?: string): Array<Collection<ModelClassBase>>;
335
+ /**
336
+ * Deletes unused indexes from all registered collections for a connection.
337
+ * Iterates over all collections registered via createCollection() and
338
+ * removes indexes that exist in MongoDB but are not defined in the collection configuration.
339
+ *
340
+ * @param connectionName - The name of the MongoDB connection (defaults to 'main')
341
+ * @returns Array of results for each collection that had indexes deleted
342
+ *
343
+ * @example
344
+ * ```ts
345
+ * // Delete unused indexes from all collections on the main connection
346
+ * const results = await deleteAllUnusedIndexes()
347
+ *
348
+ * // Delete unused indexes from all collections on a specific connection
349
+ * const results = await deleteAllUnusedIndexes('secondary')
350
+ *
351
+ * // Log results
352
+ * for (const result of results) {
353
+ * console.log(`${result.collectionName}: deleted ${result.deletedIndexes.length} indexes`)
354
+ * }
355
+ * ```
356
+ */
357
+ declare function deleteAllUnusedIndexes(connectionName?: string): Promise<DeleteUnusedIndexesResult[]>;
358
+
307
359
  declare function getOrCreateEncryptionKey({ keyAltName, kmsProvider, masterKey, connectionName, keyVaultDatabase, keyVaultCollection, kmsProviders, }: {
308
360
  keyAltName: string;
309
361
  kmsProvider: keyof KMSProviders;
@@ -321,4 +373,4 @@ declare const ENCRYPTION_ALGORITHMS: {
321
373
  RANDOM: string;
322
374
  };
323
375
 
324
- export { BaseCollection, Collection, type CollectionIndex, type CountDocuments, type CreateCollectionOptions, type CreateCollectionOptionsWithSchemaType, type CreateCollectionOptionsWithTypedSchema, DataLoader, type DeleteMany, type DeleteOne, type DistinctDocumentId, type DocumentWithId, ENCRYPTION_ALGORITHMS, type EstimatedDocumentCount, type Find, type FindCursor, type FindOne, type FindOneAndUpdate, type FindOneAndUpdateUpdateOptions, type InferIdType, type InferSchemaTypeWithId, type InitItem, type InsertAndFind, type InsertMany, type InsertManyOptions, type InsertOne, type InsertOptions, type ModelClassBase, type ModelToMongoSelector, MongoCollection, type MongoFilter, type MongoSelector, type OptionalId, Repository, type SchemaWithRequiredId, type TypedId, type UpdateAndFind, type UpdateItem, type UpdateMany, type UpdateOne, type UpdateOptions, type Upsert, allConnectionPromises, configureConnection, connections, createCollection, createIndexesPromises, getDBName, getMongoConnection, getOrCreateEncryptionKey, typedId };
376
+ export { BaseCollection, Collection, type CollectionIndex, type CountDocuments, type CreateCollectionOptions, type CreateCollectionOptionsWithSchemaType, type CreateCollectionOptionsWithTypedSchema, DataLoader, type DeleteMany, type DeleteOne, type DistinctDocumentId, type DocumentWithId, ENCRYPTION_ALGORITHMS, type EstimatedDocumentCount, type Find, type FindCursor, type FindOne, type FindOneAndUpdate, type FindOneAndUpdateUpdateOptions, type InferIdType, type InferSchemaTypeWithId, type InitItem, type InsertAndFind, type InsertMany, type InsertManyOptions, type InsertOne, type InsertOptions, type ModelClassBase, type ModelToMongoSelector, MongoCollection, type MongoFilter, type MongoSelector, type OptionalId, Repository, type SchemaWithRequiredId, type TypedId, type UpdateAndFind, type UpdateItem, type UpdateMany, type UpdateOne, type UpdateOptions, type Upsert, allConnectionPromises, collectionsRegistry, configureConnection, connections, createCollection, createIndexesPromises, deleteAllUnusedIndexes, getDBName, getMongoConnection, getOrCreateEncryptionKey, getRegisteredCollections, registerCollection, typedId };
package/dist/index.js CHANGED
@@ -1280,6 +1280,43 @@ async function loadIndexes(collection) {
1280
1280
  return results;
1281
1281
  }
1282
1282
 
1283
+ // src/createCollection/collectionsRegistry.ts
1284
+ import { logger as logger4 } from "@orion-js/logger";
1285
+ var collectionsRegistry = /* @__PURE__ */ new Map();
1286
+ function registerCollection(connectionName, collection) {
1287
+ if (!collectionsRegistry.has(connectionName)) {
1288
+ collectionsRegistry.set(connectionName, /* @__PURE__ */ new Map());
1289
+ }
1290
+ collectionsRegistry.get(connectionName).set(collection.name, collection);
1291
+ }
1292
+ function getRegisteredCollections(connectionName = "main") {
1293
+ const connectionCollections = collectionsRegistry.get(connectionName);
1294
+ if (!connectionCollections) {
1295
+ return [];
1296
+ }
1297
+ return Array.from(connectionCollections.values());
1298
+ }
1299
+ async function deleteAllUnusedIndexes(connectionName = "main") {
1300
+ const collections = getRegisteredCollections(connectionName);
1301
+ if (collections.length === 0) {
1302
+ logger4.warn(`No collections registered for connection "${connectionName}"`);
1303
+ return [];
1304
+ }
1305
+ logger4.info(
1306
+ `Deleting unused indexes from ${collections.length} collections on connection "${connectionName}"`
1307
+ );
1308
+ const results = [];
1309
+ for (const collection of collections) {
1310
+ const result = await collection.deleteUnusedIndexes();
1311
+ if (result.deletedIndexes.length > 0) {
1312
+ results.push(result);
1313
+ }
1314
+ }
1315
+ const totalDeleted = results.reduce((sum, r) => sum + r.deletedIndexes.length, 0);
1316
+ logger4.info(`Deleted ${totalDeleted} unused indexes from ${results.length} collections`);
1317
+ return results;
1318
+ }
1319
+
1283
1320
  // src/createCollection/getSchemaAndModel.ts
1284
1321
  import { clone as clone3 } from "@orion-js/helpers";
1285
1322
  Symbol.metadata ?? (Symbol.metadata = Symbol("Symbol.metadata"));
@@ -1312,7 +1349,7 @@ function getSchema(options) {
1312
1349
  }
1313
1350
 
1314
1351
  // src/createCollection/wrapMethods.ts
1315
- import { logger as logger4 } from "@orion-js/logger";
1352
+ import { logger as logger5 } from "@orion-js/logger";
1316
1353
  function wrapMethods(collection) {
1317
1354
  const methodsWithPromises = [
1318
1355
  "findOne",
@@ -1348,7 +1385,7 @@ function wrapMethods(collection) {
1348
1385
  collection[methodName2] = (...args) => {
1349
1386
  collection.startConnection();
1350
1387
  if (!collection.rawCollection) {
1351
- logger4.error("Method called before connection was initialized", {
1388
+ logger5.error("Method called before connection was initialized", {
1352
1389
  collectionName: collection.name,
1353
1390
  connectionName: collection.connectionName,
1354
1391
  methodName: methodName2
@@ -1458,6 +1495,7 @@ function createCollection(options) {
1458
1495
  }
1459
1496
  wrapMethods(mainCollection);
1460
1497
  wrapMethods(encryptedCollection);
1498
+ registerCollection(connectionName, mainCollection);
1461
1499
  return mainCollection;
1462
1500
  }
1463
1501
 
@@ -1488,7 +1526,7 @@ function MongoCollection(options) {
1488
1526
  }
1489
1527
 
1490
1528
  // src/encrypted/getOrCreateEncryptionKey.ts
1491
- import { logger as logger5 } from "@orion-js/logger";
1529
+ import { logger as logger6 } from "@orion-js/logger";
1492
1530
  import { ClientEncryption, MongoClient as MongoClient2 } from "mongodb";
1493
1531
  async function getOrCreateEncryptionKey({
1494
1532
  keyAltName,
@@ -1500,7 +1538,7 @@ async function getOrCreateEncryptionKey({
1500
1538
  kmsProviders
1501
1539
  }) {
1502
1540
  const keyVaultNamespace = `${keyVaultDatabase}.${keyVaultCollection}`;
1503
- logger5.info("Connecting to database to get or create the encryption key", {
1541
+ logger6.info("Connecting to database to get or create the encryption key", {
1504
1542
  keyVaultNamespace,
1505
1543
  keyAltName
1506
1544
  });
@@ -1518,14 +1556,14 @@ async function getOrCreateEncryptionKey({
1518
1556
  });
1519
1557
  const key = await clientEncryption.getKeyByAltName(keyAltName);
1520
1558
  if (key) {
1521
- logger5.info("Key found on the key vault", {
1559
+ logger6.info("Key found on the key vault", {
1522
1560
  keyVaultNamespace,
1523
1561
  keyAltName,
1524
1562
  UUID: key._id
1525
1563
  });
1526
1564
  return { key: key._id, keyVaultNamespace };
1527
1565
  }
1528
- logger5.info("Key not found on the key vault, creating a new one", {
1566
+ logger6.info("Key not found on the key vault, creating a new one", {
1529
1567
  keyVaultNamespace,
1530
1568
  keyAltName
1531
1569
  });
@@ -1533,7 +1571,7 @@ async function getOrCreateEncryptionKey({
1533
1571
  keyAltNames: [keyAltName],
1534
1572
  ...masterKey ? { masterKey } : {}
1535
1573
  });
1536
- logger5.info("New encryption key created", {
1574
+ logger6.info("New encryption key created", {
1537
1575
  keyVaultNamespace,
1538
1576
  keyAltName,
1539
1577
  UUID: newKey
@@ -1552,13 +1590,17 @@ export {
1552
1590
  MongoDB,
1553
1591
  Repository,
1554
1592
  allConnectionPromises,
1593
+ collectionsRegistry,
1555
1594
  configureConnection,
1556
1595
  connections,
1557
1596
  createCollection,
1558
1597
  createIndexesPromises,
1598
+ deleteAllUnusedIndexes,
1559
1599
  getDBName,
1560
1600
  getMongoConnection,
1561
1601
  getOrCreateEncryptionKey,
1602
+ getRegisteredCollections,
1603
+ registerCollection,
1562
1604
  typedId
1563
1605
  };
1564
1606
  //# sourceMappingURL=index.js.map