@orion-js/mongodb 4.3.1 → 4.5.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/dist/connect/connections.d.ts +56 -0
  3. package/dist/connect/getDBName.d.ts +1 -0
  4. package/dist/connect/getMongoConnection.d.ts +8 -0
  5. package/dist/connect/getMongoURLFromEnv.d.ts +2 -0
  6. package/dist/connect/index.d.ts +4 -0
  7. package/dist/createCollection/collectionsRegistry.d.ts +58 -0
  8. package/dist/createCollection/createIndexes.d.ts +12 -0
  9. package/dist/createCollection/deleteUnusedIndexes.d.ts +45 -0
  10. package/dist/createCollection/generateId.d.ts +3 -0
  11. package/dist/createCollection/getIndexOptions.d.ts +30 -0
  12. package/dist/createCollection/getMethods/cleanModifier.d.ts +5 -0
  13. package/dist/createCollection/getMethods/countDocuments.d.ts +2 -0
  14. package/dist/createCollection/getMethods/dataLoader/dataLoad/getDataLoader.d.ts +9 -0
  15. package/dist/createCollection/getMethods/dataLoader/dataLoad/index.d.ts +9 -0
  16. package/dist/createCollection/getMethods/dataLoader/index.d.ts +5 -0
  17. package/dist/createCollection/getMethods/dataLoader/loadById.d.ts +2 -0
  18. package/dist/createCollection/getMethods/dataLoader/loadData.d.ts +2 -0
  19. package/dist/createCollection/getMethods/dataLoader/loadMany.d.ts +2 -0
  20. package/dist/createCollection/getMethods/dataLoader/loadOne.d.ts +2 -0
  21. package/dist/createCollection/getMethods/deleteMany.d.ts +2 -0
  22. package/dist/createCollection/getMethods/deleteOne.d.ts +2 -0
  23. package/dist/createCollection/getMethods/estimatedDocumentCount.d.ts +3 -0
  24. package/dist/createCollection/getMethods/find.d.ts +2 -0
  25. package/dist/createCollection/getMethods/findOne.d.ts +2 -0
  26. package/dist/createCollection/getMethods/findOneAndUpdate.d.ts +3 -0
  27. package/dist/createCollection/getMethods/getSelector.d.ts +3 -0
  28. package/dist/createCollection/getMethods/index.d.ts +16 -0
  29. package/dist/createCollection/getMethods/insertAndFind.d.ts +3 -0
  30. package/dist/createCollection/getMethods/insertMany.d.ts +3 -0
  31. package/dist/createCollection/getMethods/insertOne.d.ts +3 -0
  32. package/dist/createCollection/getMethods/updateAndFind.d.ts +3 -0
  33. package/dist/createCollection/getMethods/updateItem.d.ts +2 -0
  34. package/dist/createCollection/getMethods/updateMany.d.ts +3 -0
  35. package/dist/createCollection/getMethods/updateOne.d.ts +3 -0
  36. package/dist/createCollection/getMethods/upsert.d.ts +3 -0
  37. package/dist/createCollection/getMethods/validateModifier/index.d.ts +1 -0
  38. package/dist/createCollection/getMethods/validateModifier/validateInc.d.ts +7 -0
  39. package/dist/createCollection/getMethods/validateModifier/validateOperator.d.ts +5 -0
  40. package/dist/createCollection/getMethods/validateModifier/validatePush.d.ts +8 -0
  41. package/dist/createCollection/getMethods/validateModifier/validateSet.d.ts +7 -0
  42. package/dist/createCollection/getMethods/validateModifier/validateUnset.d.ts +7 -0
  43. package/dist/createCollection/getMethods/validateModifier/validateUpsert.d.ts +1 -0
  44. package/dist/createCollection/getMethods/wrapErrors.d.ts +1 -0
  45. package/dist/createCollection/getSchemaAndModel.d.ts +4 -0
  46. package/dist/createCollection/index.d.ts +10 -0
  47. package/dist/createCollection/wrapMethods.d.ts +2 -0
  48. package/dist/encrypted/getOrCreateEncryptionKey.d.ts +17 -0
  49. package/dist/helpers/fromDot.d.ts +1 -0
  50. package/dist/helpers/toDot.d.ts +1 -0
  51. package/dist/index.cjs +102 -95
  52. package/dist/index.cjs.map +1 -1
  53. package/dist/index.d.ts +6 -391
  54. package/dist/index.js +92 -85
  55. package/dist/index.js.map +1 -1
  56. package/dist/service/index.d.ts +3 -0
  57. package/dist/types/index.d.ts +233 -0
  58. package/package.json +18 -19
  59. package/dist/index.d.cts +0 -391
package/dist/index.d.ts CHANGED
@@ -1,391 +1,6 @@
1
- import * as MongoDB from 'mongodb';
2
- import { MongoClient, Db, MongoClientOptions, EnhancedOmit, KMSProviders, AWSEncryptionKeyOptions, UUID } from 'mongodb';
3
- export { MongoDB };
4
- import { Schema, SchemaInAnyOrionForm, StrictInferSchemaType, TypedSchemaOnSchema, InferSchemaType, FieldType } from '@orion-js/schema';
5
-
6
- interface OrionMongoClient {
7
- client: MongoClient;
8
- db: Db;
9
- uri: string;
10
- dbName: string;
11
- /**
12
- * @deprecated Use startConnection() instead. This property is not guaranteed to be resolved if the connection is not started.
13
- * When using async calls startConnection or connectionPromise is no longer needed. Orion will automatically start the connection if it is not already started.
14
- * Kept for backwards compatibility. startConnection does not re-start the connection if it is already started, so it is safe to use.
15
- */
16
- connectionPromise: Promise<MongoClient>;
17
- connectionName: string;
18
- encrypted: {
19
- client: MongoClient;
20
- db: Db;
21
- };
22
- /**
23
- * Starts the connection if it is not already started.
24
- * If the connection is already started, it resolves immediately.
25
- */
26
- startConnection: () => Promise<MongoClient>;
27
- closeConnection: () => Promise<void>;
28
- }
29
- declare class OrionMongoDatabaseWrapper implements OrionMongoClient {
30
- uri: string;
31
- dbName: string;
32
- connectionName: string;
33
- connectionPromise: Promise<MongoClient>;
34
- private mongoOptions;
35
- private connectionEvent;
36
- private state;
37
- client: MongoClient;
38
- db: Db;
39
- configured: boolean;
40
- readonly encrypted: {
41
- client: MongoClient;
42
- db: Db;
43
- };
44
- readonly configTimeout: NodeJS.Timeout;
45
- constructor(connectionName: string);
46
- config(mongoURL: string, mongoOptions: MongoClientOptions): void;
47
- awaitConnection(): Promise<this>;
48
- connectWithRetry(client: MongoClient): Promise<MongoClient>;
49
- startConnection(): Promise<MongoClient>;
50
- closeConnection(): Promise<void>;
51
- }
52
- declare function configureConnection(connectionName: string, mongoOptions: MongoClientOptions): Promise<OrionMongoDatabaseWrapper>;
53
- declare const connections: {
54
- [key: string]: OrionMongoDatabaseWrapper;
55
- };
56
-
57
- declare const allConnectionPromises: any[];
58
- interface MongoConnectOptions {
59
- name: string;
60
- uri?: string;
61
- }
62
- declare const getMongoConnection: ({ name, uri }: MongoConnectOptions) => OrionMongoClient;
63
-
64
- declare function getDBName(url: string): string;
65
-
66
- type OptionalId<T> = MongoDB.OptionalId<T>;
67
- declare type InferIdType<TSchema> = TSchema extends {
68
- _id: infer IdType;
69
- } ? Record<any, never> extends IdType ? never : IdType : TSchema extends {
70
- _id?: infer IdType;
71
- } ? unknown extends IdType ? string : IdType : string;
72
- type DocumentWithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {
73
- _id: InferIdType<TSchema>;
74
- };
75
- type ModelClassBase = DocumentWithId<MongoDB.Document>;
76
- /**
77
- * Index definition for a MongoDB collection.
78
- * Supports flat options (recommended) or nested options object (deprecated).
79
- *
80
- * @example New format (recommended):
81
- * ```ts
82
- * { keys: { email: 1 }, unique: true, sparse: true }
83
- * ```
84
- *
85
- * @example Old format (deprecated):
86
- * ```ts
87
- * { keys: { email: 1 }, options: { unique: true, sparse: true } }
88
- * ```
89
- */
90
- interface CollectionIndex extends Partial<MongoDB.CreateIndexesOptions> {
91
- keys: MongoDB.IndexSpecification;
92
- /**
93
- * @deprecated Use flat options instead. Example: `{ keys: { email: 1 }, unique: true }`
94
- * instead of `{ keys: { email: 1 }, options: { unique: true } }`
95
- */
96
- options?: MongoDB.CreateIndexesOptions;
97
- }
98
- declare namespace DataLoader {
99
- interface LoadDataOptionsBase<ModelClass extends ModelClassBase> {
100
- key: keyof ModelClass;
101
- match?: MongoFilter<ModelClass>;
102
- sort?: MongoDB.Sort;
103
- project?: MongoDB.Document;
104
- timeout?: number;
105
- debug?: boolean;
106
- }
107
- export interface LoadDataOptions<ModelClass extends ModelClassBase> extends LoadDataOptionsBase<ModelClass> {
108
- value?: any;
109
- values?: Array<any>;
110
- }
111
- export interface LoadOneOptions<ModelClass extends ModelClassBase> extends LoadDataOptionsBase<ModelClass> {
112
- value: any;
113
- }
114
- export type LoadData<ModelClass extends ModelClassBase> = (options: LoadDataOptions<ModelClass>) => Promise<Array<ModelClass>>;
115
- export type LoadOne<ModelClass extends ModelClassBase> = (options: LoadOneOptions<ModelClass>) => Promise<ModelClass>;
116
- export type LoadMany<ModelClass extends ModelClassBase> = (options: LoadDataOptions<ModelClass>) => Promise<Array<ModelClass>>;
117
- export type LoadById<ModelClass extends ModelClassBase> = (id: ModelClass['_id']) => Promise<ModelClass>;
118
- export { };
119
- }
120
- type MongoFilter<ModelClass extends ModelClassBase = ModelClassBase> = MongoDB.Filter<ModelClass>;
121
- type MongoSelector<ModelClass extends ModelClassBase = ModelClassBase> = ModelClass['_id'] | MongoFilter<ModelClass>;
122
- interface FindCursor<ModelClass> extends MongoDB.FindCursor {
123
- toArray: () => Promise<Array<ModelClass>>;
124
- }
125
- interface UpdateOptions {
126
- clean?: boolean;
127
- validate?: boolean;
128
- mongoOptions?: MongoDB.UpdateOptions;
129
- }
130
- interface FindOneAndUpdateUpdateOptions {
131
- clean?: boolean;
132
- validate?: boolean;
133
- mongoOptions?: MongoDB.FindOneAndUpdateOptions;
134
- }
135
- interface InsertOptions {
136
- clean?: boolean;
137
- validate?: boolean;
138
- mongoOptions?: MongoDB.InsertOneOptions;
139
- }
140
- interface InsertManyOptions {
141
- clean?: boolean;
142
- validate?: boolean;
143
- mongoOptions?: MongoDB.BulkWriteOptions;
144
- }
145
- type InitItem<ModelClass extends ModelClassBase> = (doc: any) => ModelClass;
146
- type ModelToMongoSelector<ModelClass extends ModelClassBase> = MongoDB.Filter<ModelClass> | DocumentWithId<ModelClass>['_id'];
147
- type FindOne<ModelClass extends ModelClassBase> = (selector?: ModelToMongoSelector<ModelClass>, options?: MongoDB.FindOptions<ModelClass>) => Promise<ModelClass>;
148
- type Find<ModelClass extends ModelClassBase> = (selector?: ModelToMongoSelector<ModelClass>, options?: MongoDB.FindOptions<ModelClass>) => FindCursor<ModelClass>;
149
- type FindOneAndUpdate<ModelClass extends ModelClassBase> = <TSelector extends ModelToMongoSelector<ModelClass>, TFilter extends MongoDB.UpdateFilter<ModelClass>, TOptions extends FindOneAndUpdateUpdateOptions>(selector: TSelector, modifier: TFilter, options?: TOptions) => ReturnType<MongoDB.Collection<ModelClass>['findOneAndUpdate']>;
150
- type UpdateAndFind<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, modifier: MongoDB.UpdateFilter<ModelClass>, options?: FindOneAndUpdateUpdateOptions) => Promise<ModelClass>;
151
- type UpdateItem<ModelClass extends ModelClassBase> = (item: ModelClass, modifier: MongoDB.UpdateFilter<ModelClass>, options?: FindOneAndUpdateUpdateOptions) => Promise<void>;
152
- type InsertOne<ModelClass extends ModelClassBase> = (doc: MongoDB.OptionalId<ModelClass>, options?: InsertOptions) => Promise<ModelClass['_id']>;
153
- type InsertMany<ModelClass extends ModelClassBase> = (doc: Array<MongoDB.OptionalId<ModelClass>>, options?: InsertManyOptions) => Promise<Array<ModelClass['_id']>>;
154
- type InsertAndFind<ModelClass extends ModelClassBase> = (doc: MongoDB.OptionalId<ModelClass>, options?: InsertOptions) => Promise<ModelClass>;
155
- type DeleteMany<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, options?: MongoDB.DeleteOptions) => Promise<MongoDB.DeleteResult>;
156
- type DeleteOne<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, options?: MongoDB.DeleteOptions) => Promise<MongoDB.DeleteResult>;
157
- type UpdateOne<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, modifier: MongoDB.UpdateFilter<ModelClass>, options?: UpdateOptions) => Promise<MongoDB.UpdateResult>;
158
- type UpdateMany<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, modifier: MongoDB.UpdateFilter<ModelClass>, options?: UpdateOptions) => Promise<MongoDB.UpdateResult | MongoDB.Document>;
159
- type Upsert<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, modifier: MongoDB.UpdateFilter<ModelClass>, options?: UpdateOptions) => Promise<MongoDB.UpdateResult>;
160
- interface CreateCollectionOptions<ModelClass extends ModelClassBase = ModelClassBase> {
161
- /**
162
- * The name of the collection on the Mongo Database
163
- */
164
- name: string;
165
- /**
166
- * The name of the connection to use. The Mongo URL of this connection will be search on env variables.
167
- * If not found, the connection url will be `env.mongo_url`
168
- * If defined, the connection url will be `env.mongo_url_${name}`
169
- */
170
- connectionName?: string;
171
- /**
172
- * The schema used for cleaning and validation of the documents
173
- */
174
- schema?: SchemaInAnyOrionForm;
175
- /**
176
- * The indexes to use
177
- */
178
- indexes?: Array<CollectionIndex>;
179
- /**
180
- * Select between random id generation o mongo (time based) id generation
181
- */
182
- idGeneration?: 'mongo' | 'random' | 'uuid';
183
- /**
184
- * ID prefix. idGeneration will be forced to random. Recommended for type checking
185
- */
186
- idPrefix?: ModelClass['_id'];
187
- }
188
- type EstimatedDocumentCount<_ModelClass extends ModelClassBase> = (options?: MongoDB.EstimatedDocumentCountOptions) => Promise<number>;
189
- type CountDocuments<ModelClass extends ModelClassBase> = (selector: ModelToMongoSelector<ModelClass>, options?: MongoDB.CountDocumentsOptions) => Promise<number>;
190
- type SchemaWithRequiredId = Schema & {
191
- _id: {
192
- type: any;
193
- };
194
- };
195
- type InferSchemaTypeWithId<TSchema extends SchemaWithRequiredId> = DocumentWithId<StrictInferSchemaType<TSchema>>;
196
- type CreateCollectionOptionsWithSchemaType<T extends SchemaWithRequiredId> = {
197
- schema: T;
198
- } & Omit<CreateCollectionOptions<InferSchemaTypeWithId<T>>, 'schema'>;
199
- type CreateCollectionOptionsWithTypedSchema<T extends TypedSchemaOnSchema & {
200
- prototype: {
201
- _id: string;
202
- };
203
- }> = {
204
- schema: T;
205
- } & Omit<CreateCollectionOptions<InferSchemaType<T>>, 'schema'>;
206
- declare class BaseCollection<ModelClass extends ModelClassBase = ModelClassBase> {
207
- name: string;
208
- connectionName?: string;
209
- schema?: Schema;
210
- generateId: () => ModelClass['_id'];
211
- getSchema: () => Schema;
212
- db: MongoDB.Db;
213
- client: OrionMongoClient;
214
- /**
215
- * @deprecated Use getRawCollection() instead. This property is not guaranteed to be defined if the connection has not been started.
216
- */
217
- rawCollection: MongoDB.Collection<ModelClass>;
218
- getRawCollection: () => Promise<MongoDB.Collection<ModelClass>>;
219
- findOne: FindOne<ModelClass>;
220
- find: Find<ModelClass>;
221
- insertOne: InsertOne<ModelClass>;
222
- insertMany: InsertMany<ModelClass>;
223
- insertAndFind: InsertAndFind<ModelClass>;
224
- deleteMany: DeleteMany<ModelClass>;
225
- deleteOne: DeleteOne<ModelClass>;
226
- updateOne: UpdateOne<ModelClass>;
227
- updateMany: UpdateMany<ModelClass>;
228
- upsert: Upsert<ModelClass>;
229
- findOneAndUpdate: FindOneAndUpdate<ModelClass>;
230
- /**
231
- * Updates a document and returns the updated document with the changes
232
- */
233
- updateAndFind: UpdateAndFind<ModelClass>;
234
- updateItem: UpdateItem<ModelClass>;
235
- estimatedDocumentCount: EstimatedDocumentCount<ModelClass>;
236
- countDocuments: CountDocuments<ModelClass>;
237
- aggregate: <T = MongoDB.Document>(pipeline?: MongoDB.Document[], options?: MongoDB.AggregateOptions) => MongoDB.AggregationCursor<T>;
238
- watch: <T = MongoDB.Document>(pipeline?: MongoDB.Document[], options?: MongoDB.ChangeStreamOptions) => MongoDB.ChangeStream<T>;
239
- loadData: DataLoader.LoadData<ModelClass>;
240
- loadOne: DataLoader.LoadOne<ModelClass>;
241
- loadMany: DataLoader.LoadMany<ModelClass>;
242
- loadById: DataLoader.LoadById<ModelClass>;
243
- /**
244
- * Use this function if you are using tests and you pass the
245
- * env var DONT_CREATE_INDEXES_AUTOMATICALLY and you need to
246
- * create the indexes for this collection
247
- */
248
- createIndexes: () => Promise<string[]>;
249
- createIndexesPromise: Promise<string[]>;
250
- /**
251
- * Deletes indexes that exist in MongoDB but are not defined in the collection configuration.
252
- * This helps clean up stale indexes that are no longer needed.
253
- * Always preserves the _id_ index.
254
- */
255
- deleteUnusedIndexes: () => Promise<{
256
- deletedIndexes: string[];
257
- collectionName: string;
258
- }>;
259
- /**
260
- * @deprecated Use startConnection() instead. This property is not guaranteed to be resolved if the connection is not started.
261
- * When using async calls startConnection or connectionPromise is no longer needed. Orion will automatically start the connection if it is not already started.
262
- * Kept for backwards compatibility. startConnection does not re-start the connection if it is already started, so it is safe to use.
263
- */
264
- connectionPromise: Promise<MongoDB.MongoClient>;
265
- startConnection: () => Promise<MongoDB.MongoClient>;
266
- }
267
- declare class Collection<ModelClass extends ModelClassBase = ModelClassBase> extends BaseCollection<ModelClass> {
268
- indexes: Array<CollectionIndex>;
269
- encrypted?: BaseCollection<ModelClass>;
270
- }
271
- type DistinctDocumentId<DistinctId extends string> = string & {
272
- __TYPE__: `DistinctDocumentId<${DistinctId}>`;
273
- };
274
- type TypedId<TPrefix extends string> = `${TPrefix}-${string}`;
275
- /**
276
- * Use this function to create unique types for the ids of mongodb documents.
277
- * You should set it as the type of the _id field in your schema.
278
- *
279
- * @example
280
- * ```ts
281
- * type UserId = TypedId<'user'>
282
- *
283
- * const userSchema = {
284
- * _id: {
285
- * type: TypedId('user'),
286
- * },
287
- * }
288
- *
289
- * ```
290
- */
291
- declare function typedId<const TPrefix extends string>(prefix: TPrefix): FieldType<TypedId<TPrefix>> & {
292
- generateId: () => TypedId<TPrefix>;
293
- };
294
-
295
- declare function Repository(): (target: any, context: ClassDecoratorContext<any>) => void;
296
- declare function MongoCollection<ModelClass extends ModelClassBase = ModelClassBase>(options: CreateCollectionOptions<ModelClass>): (_target: any, context: ClassFieldDecoratorContext) => void;
297
-
298
- declare const createIndexesPromises: any[];
299
- declare function createCollection<T extends SchemaWithRequiredId>(options: CreateCollectionOptionsWithSchemaType<T>): Collection<InferSchemaTypeWithId<T>>;
300
- declare function createCollection<T extends TypedSchemaOnSchema & {
301
- prototype: {
302
- _id: string;
303
- };
304
- }>(options: CreateCollectionOptionsWithTypedSchema<T>): Collection<InferSchemaType<T>>;
305
- declare function createCollection<T extends ModelClassBase>(options: CreateCollectionOptions<T>): Collection<T>;
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
- * When the same collection is registered multiple times, indexes are merged.
321
- */
322
- declare const collectionsRegistry: Map<string, Map<string, Collection<ModelClassBase>>>;
323
- /**
324
- * Registers a collection in the registry.
325
- * Called automatically when a collection is created via createCollection().
326
- * If the same collection name is registered multiple times, indexes are merged
327
- * to support multiple createCollection() calls for the same collection.
328
- * @param connectionName - The name of the MongoDB connection
329
- * @param collection - The collection instance to register
330
- */
331
- declare function registerCollection(connectionName: string, collection: Collection<ModelClassBase>): void;
332
- /**
333
- * Gets all registered collections for a specific connection.
334
- * @param connectionName - The name of the MongoDB connection (defaults to 'main')
335
- * @returns Array of registered collections for the connection
336
- */
337
- declare function getRegisteredCollections(connectionName?: string): Array<Collection<ModelClassBase>>;
338
- /**
339
- * Gets the merged indexes for a specific collection from the registry.
340
- * This includes all indexes from all createCollection() calls for the same collection name.
341
- * @param connectionName - The name of the MongoDB connection
342
- * @param collectionName - The name of the collection
343
- * @returns Array of merged index definitions, or empty array if collection not registered
344
- */
345
- declare function getMergedIndexes(connectionName: string, collectionName: string): CollectionIndex[];
346
- /**
347
- * Deletes unused indexes from all registered collections for a connection.
348
- * Iterates over all collections registered via createCollection() and
349
- * removes indexes that exist in MongoDB but are not defined in the collection configuration.
350
- *
351
- * **Important**: This function waits for all pending index creation to complete before
352
- * deleting any indexes, to avoid race conditions where an index being created might
353
- * be incorrectly identified as unused.
354
- *
355
- * @param connectionName - The name of the MongoDB connection (defaults to 'main')
356
- * @returns Array of results for each collection that had indexes deleted
357
- *
358
- * @example
359
- * ```ts
360
- * // Delete unused indexes from all collections on the main connection
361
- * const results = await deleteAllUnusedIndexes()
362
- *
363
- * // Delete unused indexes from all collections on a specific connection
364
- * const results = await deleteAllUnusedIndexes('secondary')
365
- *
366
- * // Log results
367
- * for (const result of results) {
368
- * console.log(`${result.collectionName}: deleted ${result.deletedIndexes.length} indexes`)
369
- * }
370
- * ```
371
- */
372
- declare function deleteAllUnusedIndexes(connectionName?: string): Promise<DeleteUnusedIndexesResult[]>;
373
-
374
- declare function getOrCreateEncryptionKey({ keyAltName, kmsProvider, masterKey, connectionName, keyVaultDatabase, keyVaultCollection, kmsProviders, }: {
375
- keyAltName: string;
376
- kmsProvider: keyof KMSProviders;
377
- masterKey?: AWSEncryptionKeyOptions;
378
- connectionName?: string;
379
- keyVaultDatabase?: string;
380
- keyVaultCollection?: string;
381
- kmsProviders: KMSProviders;
382
- }): Promise<{
383
- key: UUID;
384
- keyVaultNamespace: string;
385
- }>;
386
- declare const ENCRYPTION_ALGORITHMS: {
387
- DETERMINISTIC: string;
388
- RANDOM: string;
389
- };
390
-
391
- 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, getMergedIndexes, getMongoConnection, getOrCreateEncryptionKey, getRegisteredCollections, registerCollection, typedId };
1
+ export * from './connect';
2
+ export * from './types';
3
+ export * from './service';
4
+ export * from './createCollection';
5
+ export * from './createCollection/collectionsRegistry';
6
+ export * from './encrypted/getOrCreateEncryptionKey';
package/dist/index.js CHANGED
@@ -489,8 +489,8 @@ function findOne_default(collection) {
489
489
  return findOne;
490
490
  }
491
491
 
492
- // src/createCollection/getMethods/validateModifier/validatePush.ts
493
- import { validate } from "@orion-js/schema";
492
+ // src/createCollection/getMethods/cleanModifier.ts
493
+ import { cleanKey, clean } from "@orion-js/schema";
494
494
 
495
495
  // src/helpers/fromDot.ts
496
496
  import dot2 from "dot-object";
@@ -508,7 +508,70 @@ function fromDot(doc) {
508
508
  return dot2.object(doc);
509
509
  }
510
510
 
511
+ // src/createCollection/getMethods/cleanModifier.ts
512
+ var shouldCheck = (key) => {
513
+ if (key === "$pushAll") throw new Error("$pushAll is not supported; use $push + $each");
514
+ return ["$pull", "$pullAll", "$pop", "$slice"].indexOf(key) === -1;
515
+ };
516
+ async function cleanModifier(schema, modifier, { isUpsert } = { isUpsert: false }) {
517
+ const cleanedModifier = {};
518
+ for (const operation of Object.keys(modifier)) {
519
+ const operationDoc = modifier[operation];
520
+ cleanedModifier[operation] = {};
521
+ if (operation.slice(0, 1) !== "$") {
522
+ throw new Error(`Expected '${operation}' to be a modifier operator like '$set'`);
523
+ }
524
+ if (!shouldCheck(operation)) {
525
+ cleanedModifier[operation] = operationDoc;
526
+ continue;
527
+ }
528
+ for (const key of Object.keys(operationDoc)) {
529
+ const value = operationDoc[key];
530
+ const cleanOptions = { forceDoc: operationDoc };
531
+ let cleaned = null;
532
+ if (operation === "$push" || operation === "$addToSet") {
533
+ if (typeof value === "object" && "$each" in value) {
534
+ const $each = await cleanKey(schema, key, value.$each, cleanOptions);
535
+ cleaned = { ...value, $each };
536
+ } else {
537
+ cleaned = await cleanKey(schema, `${key}.0`, value, cleanOptions);
538
+ }
539
+ }
540
+ if (operation === "$set") {
541
+ cleaned = await cleanKey(schema, key, value, cleanOptions);
542
+ }
543
+ if (operation === "$setOnInsert") {
544
+ cleaned = await cleanKey(schema, key, value, cleanOptions);
545
+ }
546
+ if (operation === "$inc") {
547
+ cleaned = await cleanKey(schema, key, value, cleanOptions);
548
+ }
549
+ if (operation === "$unset") {
550
+ const isPresent = await cleanKey(schema, key, "anyvalue", cleanOptions);
551
+ cleaned = !isNil(isPresent) ? "" : null;
552
+ }
553
+ if (cleaned !== void 0) {
554
+ cleanedModifier[operation][key] = cleaned;
555
+ }
556
+ }
557
+ if (isEmpty(cleanedModifier[operation])) {
558
+ delete cleanedModifier[operation];
559
+ }
560
+ }
561
+ if (isUpsert) {
562
+ const cleanedSetOnInsert = await clean(schema, fromDot(cleanedModifier.$setOnInsert || {}));
563
+ if (!isEmpty(cleanedSetOnInsert)) {
564
+ cleanedModifier.$setOnInsert = cleanedSetOnInsert;
565
+ }
566
+ }
567
+ if (equals(cleanedModifier, {})) {
568
+ throw new Error("After cleaning your modifier is empty");
569
+ }
570
+ return cleanedModifier;
571
+ }
572
+
511
573
  // src/createCollection/getMethods/validateModifier/validatePush.ts
574
+ import { validate } from "@orion-js/schema";
512
575
  async function validatePush_default({ schema, operationDoc, operation }) {
513
576
  for (const key of Object.keys(operationDoc)) {
514
577
  const value = operationDoc[key];
@@ -570,12 +633,12 @@ async function validateSet_default({ schema, operationDoc }) {
570
633
  }
571
634
 
572
635
  // src/createCollection/getMethods/validateModifier/validateOperator.ts
573
- var shouldCheck = function(key) {
636
+ var shouldCheck2 = function(key) {
574
637
  if (key === "$pushAll") throw new Error("$pushAll is not supported, use $push + $each");
575
638
  return ["$pull", "$pullAll", "$pop", "$slice"].indexOf(key) === -1;
576
639
  };
577
640
  async function validateOperator_default({ schema, operationDoc, operation }) {
578
- if (!shouldCheck(operation)) return;
641
+ if (!shouldCheck2(operation)) return;
579
642
  if (operation === "$set") {
580
643
  await validateSet_default({ schema, operationDoc });
581
644
  } else if (operation === "$unset") {
@@ -632,69 +695,6 @@ async function validateUpsert_default(schema, selector, modifier) {
632
695
  await validateModifier(schema, omit(["$setOnInsert"], modifier));
633
696
  }
634
697
 
635
- // src/createCollection/getMethods/cleanModifier.ts
636
- import { cleanKey, clean } from "@orion-js/schema";
637
- var shouldCheck2 = (key) => {
638
- if (key === "$pushAll") throw new Error("$pushAll is not supported; use $push + $each");
639
- return ["$pull", "$pullAll", "$pop", "$slice"].indexOf(key) === -1;
640
- };
641
- async function cleanModifier(schema, modifier, { isUpsert } = { isUpsert: false }) {
642
- const cleanedModifier = {};
643
- for (const operation of Object.keys(modifier)) {
644
- const operationDoc = modifier[operation];
645
- cleanedModifier[operation] = {};
646
- if (operation.slice(0, 1) !== "$") {
647
- throw new Error(`Expected '${operation}' to be a modifier operator like '$set'`);
648
- }
649
- if (!shouldCheck2(operation)) {
650
- cleanedModifier[operation] = operationDoc;
651
- continue;
652
- }
653
- for (const key of Object.keys(operationDoc)) {
654
- const value = operationDoc[key];
655
- const cleanOptions = { forceDoc: operationDoc };
656
- let cleaned = null;
657
- if (operation === "$push" || operation === "$addToSet") {
658
- if (typeof value === "object" && "$each" in value) {
659
- const $each = await cleanKey(schema, key, value.$each, cleanOptions);
660
- cleaned = { ...value, $each };
661
- } else {
662
- cleaned = await cleanKey(schema, `${key}.0`, value, cleanOptions);
663
- }
664
- }
665
- if (operation === "$set") {
666
- cleaned = await cleanKey(schema, key, value, cleanOptions);
667
- }
668
- if (operation === "$setOnInsert") {
669
- cleaned = await cleanKey(schema, key, value, cleanOptions);
670
- }
671
- if (operation === "$inc") {
672
- cleaned = await cleanKey(schema, key, value, cleanOptions);
673
- }
674
- if (operation === "$unset") {
675
- const isPresent = await cleanKey(schema, key, "anyvalue", cleanOptions);
676
- cleaned = !isNil(isPresent) ? "" : null;
677
- }
678
- if (cleaned !== void 0) {
679
- cleanedModifier[operation][key] = cleaned;
680
- }
681
- }
682
- if (isEmpty(cleanedModifier[operation])) {
683
- delete cleanedModifier[operation];
684
- }
685
- }
686
- if (isUpsert) {
687
- const cleanedSetOnInsert = await clean(schema, fromDot(cleanedModifier.$setOnInsert || {}));
688
- if (!isEmpty(cleanedSetOnInsert)) {
689
- cleanedModifier.$setOnInsert = cleanedSetOnInsert;
690
- }
691
- }
692
- if (equals(cleanedModifier, {})) {
693
- throw new Error("After cleaning your modifier is empty");
694
- }
695
- return cleanedModifier;
696
- }
697
-
698
698
  // src/createCollection/getMethods/wrapErrors.ts
699
699
  import { ValidationError as ValidationError3 } from "@orion-js/schema";
700
700
  var wrapErrors = async (operation) => {
@@ -723,10 +723,10 @@ var wrapErrors = async (operation) => {
723
723
 
724
724
  // src/createCollection/getMethods/upsert.ts
725
725
  var upsert_default = (collection) => {
726
- const upsert = async function(selectorArg, modifierArg, options = {}) {
726
+ const upsert = async (selectorArg, modifierArg, options = {}) => {
727
727
  await collection.connectionPromise;
728
728
  let modifier = modifierArg;
729
- let selector = getSelector(arguments);
729
+ let selector = getSelector([selectorArg]);
730
730
  modifier.$setOnInsert = { ...modifier.$setOnInsert, _id: collection.generateId() };
731
731
  if (collection.schema) {
732
732
  const schema = collection.getSchema();
@@ -817,16 +817,17 @@ var updateMany_default = (collection) => {
817
817
 
818
818
  // src/createCollection/getMethods/updateAndFind.ts
819
819
  var updateAndFind_default = (collection) => {
820
- const updateAndFind = async function(selector, modifier, options = {}) {
820
+ const updateAndFind = async (selector, modifier, options = {}) => {
821
821
  await collection.connectionPromise;
822
822
  return await wrapErrors(async () => {
823
- return await collection.findOneAndUpdate(selector, modifier, {
823
+ const result = await collection.findOneAndUpdate(selector, modifier, {
824
824
  ...options,
825
825
  mongoOptions: {
826
826
  ...options.mongoOptions,
827
827
  returnDocument: "after"
828
828
  }
829
829
  });
830
+ return result;
830
831
  });
831
832
  };
832
833
  return updateAndFind;
@@ -911,10 +912,14 @@ var insertMany_default = (collection) => {
911
912
 
912
913
  // src/createCollection/getMethods/updateItem.ts
913
914
  function updateItem_default(collection) {
914
- const updateItem = async function(item, modifier, options = {}) {
915
+ const updateItem = async (item, modifier, options = {}) => {
915
916
  await collection.connectionPromise;
916
917
  const updated = await wrapErrors(async () => {
917
- return await collection.updateAndFind(item._id, modifier, options);
918
+ return await collection.updateAndFind(
919
+ item._id,
920
+ modifier,
921
+ options
922
+ );
918
923
  });
919
924
  for (const key in item) {
920
925
  delete item[key];
@@ -1110,10 +1115,11 @@ function loadData_default(collection) {
1110
1115
  import { generateId, generateUUID } from "@orion-js/helpers";
1111
1116
  import { ObjectId } from "bson";
1112
1117
  var getIdGenerator = (options) => {
1113
- var _a, _b;
1114
- if (!options.idPrefix && ((_a = options == null ? void 0 : options.schema) == null ? void 0 : _a._id)) {
1115
- const idField = options.schema._id.type;
1116
- if ((_b = idField.name) == null ? void 0 : _b.startsWith("typedId:")) {
1118
+ var _a;
1119
+ const schema = options.schema;
1120
+ if (!options.idPrefix && (schema == null ? void 0 : schema._id)) {
1121
+ const idField = schema._id.type;
1122
+ if ((_a = idField.name) == null ? void 0 : _a.startsWith("typedId:")) {
1117
1123
  return () => {
1118
1124
  return idField.generateId();
1119
1125
  };
@@ -1384,20 +1390,21 @@ function prepareShema(schema) {
1384
1390
  function getSchema(options) {
1385
1391
  var _a;
1386
1392
  if (!options.schema) return;
1387
- if ((_a = options.schema[Symbol.metadata]) == null ? void 0 : _a._getModel) {
1388
- return options.schema[Symbol.metadata]._getModel().getSchema();
1393
+ const schemaOption = options.schema;
1394
+ if ((_a = schemaOption[Symbol.metadata]) == null ? void 0 : _a._getModel) {
1395
+ return schemaOption[Symbol.metadata]._getModel().getSchema();
1389
1396
  }
1390
- if (options.schema.getSchema) {
1391
- const schema = options.schema.getSchema();
1397
+ if (schemaOption.getSchema) {
1398
+ const schema = schemaOption.getSchema();
1392
1399
  return prepareShema(schema);
1393
1400
  }
1394
- if (options.schema.getModel) {
1395
- const model = options.schema.getModel();
1401
+ if (schemaOption.getModel) {
1402
+ const model = schemaOption.getModel();
1396
1403
  const schema = model ? clone2(model.getSchema()) : {};
1397
1404
  return prepareShema(schema);
1398
1405
  }
1399
- if (type(options.schema) === "Object") {
1400
- return prepareShema(options.schema);
1406
+ if (type(schemaOption) === "Object") {
1407
+ return prepareShema(schemaOption);
1401
1408
  }
1402
1409
  }
1403
1410