@sarmorttech/sar-db 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # nest-mongodb
2
+
3
+ ## Description
4
+
5
+ This is a MongoDB module for [NestJS](https://nestjs.com/), making it easy to inject the [MongoDB driver](https://www.npmjs.com/package/mongodb) into your project. It's modeled after the official [Mongoose module](https://github.com/nestjs/mongoose), allowing for asynchronous configuration and such.
6
+
7
+ ## Installation
8
+
9
+ In your existing NestJS-based project:
10
+
11
+ ```
12
+ $ npm install nest-mongodb mongodb
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ Overall, it works very similarly to the [Mongoose](https://docs.nestjs.com/techniques/mongodb) module described in the NestJS documentation, though without any notion of models. You may want to refer to those docs as well -- and maybe the [dependency injection](https://docs.nestjs.com/fundamentals/custom-providers) docs too if you're still trying to wrap your head around the NestJS implementation of it.
18
+
19
+ ### Simple example
20
+
21
+ In the simplest case, you can explicitly specify the database URI, name, and options you'd normally provide to your `MongoClient` using `MongoModule.forRoot()`:
22
+
23
+ ```typescript
24
+ import { Module } from '@nestjs/common'
25
+ import { MongoModule } from 'nest-mongodb'
26
+
27
+ @Module({
28
+ imports: [MongoModule.forRoot('mongodb://localhost', 'BestAppEver')]
29
+ })
30
+ export class CatsModule {}
31
+ ```
32
+
33
+ To inject the Mongo `Db` object:
34
+
35
+ ```typescript
36
+ import * as mongo from 'mongodb'
37
+ import { Injectable } from '@nestjs/common'
38
+ import { InjectDb } from 'nest-mongodb'
39
+ import { Cat } from './interfaces/cat'
40
+
41
+ @Injectable()
42
+ export class CatsRepository {
43
+ private readonly collection: mongo.Collection
44
+
45
+ constructor(@InjectDb() private readonly db: mongo.Db) {
46
+ this.collection = this.db.collection('cats')
47
+ }
48
+
49
+ async create(cat: Cat) {
50
+ const result = await this.collection.insertOne(cat)
51
+
52
+ if (result.insertedCount !== 1 || result.ops.length < 1) {
53
+ throw new Error('Insert failed!')
54
+ }
55
+
56
+ return result.ops[0]
57
+ }
58
+ }
59
+ ```
60
+
61
+ To inject a collection object:
62
+
63
+ ```typescript
64
+ import { Module } from '@nestjs/common'
65
+ import { MongoModule } from 'nest-mongodb'
66
+ import { CatsController } from './cats.controller'
67
+ import { CatsService } from './cats.service'
68
+
69
+ @Module({
70
+ imports: [MongoModule.forFeature(['cats'])],
71
+ controllers: [CatsController],
72
+ providers: [CatsService],
73
+ })
74
+ export class CatsModule {}
75
+ ```
76
+
77
+ ```typescript
78
+ import * as mongo from 'mongodb'
79
+ import { Injectable } from '@nestjs/common'
80
+ import { InjectCollection } from 'nest-mongodb'
81
+ import { Cat } from './interfaces/cat'
82
+
83
+ @Injectable()
84
+ export class CatsRepository {
85
+ constructor(@InjectCollection('cats') private readonly catsCollection: mongo.Collection) {}
86
+
87
+ async create(cat: Cat) {
88
+ const result = await this.catsCollection.insertOne(cat)
89
+
90
+ if (result.insertedCount !== 1 || result.ops.length < 1) {
91
+ throw new Error('Insert failed!')
92
+ }
93
+
94
+ return result.ops[0]
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### Asynchronous configuration
100
+
101
+ If you want to pass in Mongo configuration options from a ConfigService or other provider, you'll need to perform the Mongo module configuration asynchronously, using `MongoModule.forRootAsync()`. There are several different ways of doing this.
102
+
103
+ #### Use a factory function
104
+
105
+ The first is to specify a factory function that populates the options:
106
+
107
+ ```typescript
108
+ import { Module } from '@nestjs/common'
109
+ import { MongoModule } from 'nest-mongodb'
110
+ import { ConfigService } from '../config/config.service'
111
+
112
+ @Module({
113
+ imports: [MongoModule.forRootAsync({
114
+ imports: [ConfigModule],
115
+ useFactory: (config: ConfigService) => {
116
+ uri: config.mongoUri,
117
+ dbName: config.mongoDatabase
118
+ },
119
+ inject: [ConfigService]
120
+ })]
121
+ })
122
+ export class CatsModule {}
123
+ ```
124
+
125
+ #### Use a class
126
+
127
+ Alternatively, you can write a class that implements the `MongoOptionsFactory` interface and use that to create the options:
128
+
129
+ ```typescript
130
+ import { Module } from '@nestjs/common'
131
+ import { MongoModule, MongoOptionsFactory, MongoModuleOptions } from 'nest-mongodb'
132
+
133
+ @Injectable()
134
+ export class MongoConfigService implements MongoOptionsFactory {
135
+ private readonly uri = 'mongodb://localhost'
136
+ private readonly dbName = 'BestAppEver'
137
+
138
+ createMongoOptions(): MongoModuleOptions {
139
+ return {
140
+ uri: this.uri,
141
+ dbName: this.dbName
142
+ }
143
+ }
144
+ }
145
+
146
+ @Module({
147
+ imports: [MongoModule.forRootAsync({
148
+ useClass: MongoConfigService
149
+ })]
150
+ })
151
+ export class CatsModule {}
152
+ ```
153
+
154
+ Just be aware that the `useClass` option will instantiate your class inside the MongoModule, which may not be what you want.
155
+
156
+ #### Use existing
157
+
158
+ If you wish to instead import your MongoConfigService class from a different module, the `useExisting` option will allow you to do that.
159
+
160
+ ```typescript
161
+ import { Module } from '@nestjs/common'
162
+ import { MongoModule } from 'nest-mongodb'
163
+ import { ConfigModule, ConfigService } from '../config/config.service'
164
+
165
+ @Module({
166
+ imports: [MongoModule.forRootAsync({
167
+ imports: [ConfigModule]
168
+ useExisting: ConfigService
169
+ })]
170
+ })
171
+ export class CatsModule {}
172
+ ```
173
+
174
+ In this example, we're assuming that `ConfigService` implements the `MongoOptionsFactory` interface and can be found in the ConfigModule.
package/lib/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './mongo.decorators';
2
+ export * from './mongo.module';
3
+ export * from './mongo.util';
4
+ export * from './interfaces';
package/lib/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./mongo.decorators"), exports);
18
+ __exportStar(require("./mongo.module"), exports);
19
+ __exportStar(require("./mongo.util"), exports);
20
+ __exportStar(require("./interfaces"), exports);
@@ -0,0 +1 @@
1
+ export * from './mongo-options.interface';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./mongo-options.interface"), exports);
@@ -0,0 +1,36 @@
1
+ import { ModuleMetadata, Type } from '@nestjs/common/interfaces';
2
+ /**
3
+ * Options that ultimately need to be provided to create a MongoDB connection
4
+ */
5
+ export interface MongoModuleOptions {
6
+ connectionName?: string;
7
+ uri: string;
8
+ dbName: string;
9
+ clientOptions?: any;
10
+ }
11
+ export interface MongoOptionsFactory {
12
+ createMongoOptions(): Promise<MongoModuleOptions> | MongoModuleOptions;
13
+ }
14
+ /**
15
+ * Options available when creating the module asynchrously. You should use only one of the
16
+ * useExisting, useClass, or useFactory options for creation.
17
+ */
18
+ export interface MongoModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
19
+ /** A unique name for the connection. If not specified, a default one will be used. */
20
+ connectionName?: string;
21
+ /** Reuse an injectable factory class created in another module. */
22
+ useExisting?: Type<MongoOptionsFactory>;
23
+ /**
24
+ * Use an injectable factory class to populate the module options, such as URI and database name.
25
+ */
26
+ useClass?: Type<MongoOptionsFactory>;
27
+ /**
28
+ * A factory function that will populate the module options, such as URI and database name.
29
+ */
30
+ useFactory?: (...args: any[]) => Promise<MongoModuleOptions> | MongoModuleOptions;
31
+ /**
32
+ * Inject any dependencies required by the Mongo module, such as a configuration service
33
+ * that supplies the URI and database name
34
+ */
35
+ inject?: any[];
36
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,13 @@
1
+ import { DynamicModule, OnApplicationShutdown } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+ import { MongoModuleAsyncOptions } from './interfaces/mongo-options.interface';
4
+ export declare class MongoCoreModule implements OnApplicationShutdown {
5
+ private readonly connectionName;
6
+ private readonly moduleRef;
7
+ constructor(connectionName: string, moduleRef: ModuleRef);
8
+ static forRoot(uri: string, dbName: string, clientOptions?: any, connectionName?: string): DynamicModule;
9
+ static forRootAsync(options: MongoModuleAsyncOptions): DynamicModule;
10
+ onApplicationShutdown(): Promise<void>;
11
+ private static createAsyncProviders;
12
+ private static createAsyncOptionsProvider;
13
+ }
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
15
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
16
+ return new (P || (P = Promise))(function (resolve, reject) {
17
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
20
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
21
+ });
22
+ };
23
+ var MongoCoreModule_1;
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.MongoCoreModule = void 0;
26
+ const common_1 = require("@nestjs/common");
27
+ const core_1 = require("@nestjs/core");
28
+ const mongodb_1 = require("mongodb");
29
+ const mongo_constants_1 = require("./mongo.constants");
30
+ const mongo_util_1 = require("./mongo.util");
31
+ let MongoCoreModule = MongoCoreModule_1 = class MongoCoreModule {
32
+ constructor(connectionName, moduleRef) {
33
+ this.connectionName = connectionName;
34
+ this.moduleRef = moduleRef;
35
+ }
36
+ static forRoot(uri, dbName, clientOptions, connectionName) {
37
+ const connectionNameProvider = {
38
+ provide: mongo_constants_1.MONGO_CONNECTION_NAME,
39
+ useValue: connectionName !== null && connectionName !== void 0 ? connectionName : mongo_constants_1.DEFAULT_MONGO_CONNECTION_NAME
40
+ };
41
+ const clientProvider = {
42
+ provide: (0, mongo_util_1.getClientToken)(connectionName),
43
+ useFactory: () => __awaiter(this, void 0, void 0, function* () {
44
+ const client = new mongodb_1.MongoClient(uri, clientOptions);
45
+ return yield client.connect();
46
+ })
47
+ };
48
+ const dbProvider = {
49
+ provide: (0, mongo_util_1.getDbToken)(connectionName),
50
+ useFactory: (client) => client.db(dbName),
51
+ inject: [(0, mongo_util_1.getClientToken)(connectionName)]
52
+ };
53
+ return {
54
+ module: MongoCoreModule_1,
55
+ providers: [connectionNameProvider, clientProvider, dbProvider],
56
+ exports: [clientProvider, dbProvider]
57
+ };
58
+ }
59
+ static forRootAsync(options) {
60
+ var _a;
61
+ const mongoConnectionName = (_a = options.connectionName) !== null && _a !== void 0 ? _a : mongo_constants_1.DEFAULT_MONGO_CONNECTION_NAME;
62
+ const connectionNameProvider = {
63
+ provide: mongo_constants_1.MONGO_CONNECTION_NAME,
64
+ useValue: mongoConnectionName
65
+ };
66
+ const clientProvider = {
67
+ provide: (0, mongo_util_1.getClientToken)(mongoConnectionName),
68
+ useFactory: (mongoModuleOptions) => __awaiter(this, void 0, void 0, function* () {
69
+ const { uri, clientOptions } = mongoModuleOptions;
70
+ const client = new mongodb_1.MongoClient(uri, clientOptions);
71
+ return yield client.connect();
72
+ }),
73
+ inject: [mongo_constants_1.MONGO_MODULE_OPTIONS]
74
+ };
75
+ const dbProvider = {
76
+ provide: (0, mongo_util_1.getDbToken)(mongoConnectionName),
77
+ useFactory: (mongoModuleOptions, client) => client.db(mongoModuleOptions.dbName),
78
+ inject: [mongo_constants_1.MONGO_MODULE_OPTIONS, (0, mongo_util_1.getClientToken)(mongoConnectionName)]
79
+ };
80
+ const asyncProviders = this.createAsyncProviders(options);
81
+ return {
82
+ module: MongoCoreModule_1,
83
+ imports: options.imports,
84
+ providers: [...asyncProviders, clientProvider, dbProvider, connectionNameProvider],
85
+ exports: [clientProvider, dbProvider]
86
+ };
87
+ }
88
+ onApplicationShutdown() {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ const client = this.moduleRef.get((0, mongo_util_1.getClientToken)(this.connectionName));
91
+ if (client)
92
+ yield client.close();
93
+ });
94
+ }
95
+ static createAsyncProviders(options) {
96
+ if (options.useExisting || options.useFactory) {
97
+ return [this.createAsyncOptionsProvider(options)];
98
+ }
99
+ else if (options.useClass) {
100
+ return [
101
+ this.createAsyncOptionsProvider(options),
102
+ {
103
+ provide: options.useClass,
104
+ useClass: options.useClass
105
+ }
106
+ ];
107
+ }
108
+ else {
109
+ return [];
110
+ }
111
+ }
112
+ static createAsyncOptionsProvider(options) {
113
+ var _a;
114
+ if (options.useFactory) {
115
+ return {
116
+ provide: mongo_constants_1.MONGO_MODULE_OPTIONS,
117
+ useFactory: options.useFactory,
118
+ inject: (_a = options.inject) !== null && _a !== void 0 ? _a : []
119
+ };
120
+ }
121
+ else if (options.useExisting) {
122
+ return {
123
+ provide: mongo_constants_1.MONGO_MODULE_OPTIONS,
124
+ useFactory: (optionsFactory) => __awaiter(this, void 0, void 0, function* () { return yield optionsFactory.createMongoOptions(); }),
125
+ inject: [options.useExisting]
126
+ };
127
+ }
128
+ else if (options.useClass) {
129
+ return {
130
+ provide: mongo_constants_1.MONGO_MODULE_OPTIONS,
131
+ useFactory: (optionsFactory) => __awaiter(this, void 0, void 0, function* () { return yield optionsFactory.createMongoOptions(); }),
132
+ inject: [options.useClass]
133
+ };
134
+ }
135
+ else {
136
+ throw new Error('Invalid MongoModule options');
137
+ }
138
+ }
139
+ };
140
+ exports.MongoCoreModule = MongoCoreModule;
141
+ exports.MongoCoreModule = MongoCoreModule = MongoCoreModule_1 = __decorate([
142
+ (0, common_1.Global)(),
143
+ (0, common_1.Module)({}),
144
+ __param(0, (0, common_1.Inject)(mongo_constants_1.MONGO_CONNECTION_NAME)),
145
+ __metadata("design:paramtypes", [String, core_1.ModuleRef])
146
+ ], MongoCoreModule);
@@ -0,0 +1,3 @@
1
+ export declare const MONGO_CONNECTION_NAME = "MongoConnectionName";
2
+ export declare const MONGO_MODULE_OPTIONS = "MongoModuleOptions";
3
+ export declare const DEFAULT_MONGO_CONNECTION_NAME = "DefaultMongo";
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_MONGO_CONNECTION_NAME = exports.MONGO_MODULE_OPTIONS = exports.MONGO_CONNECTION_NAME = void 0;
4
+ exports.MONGO_CONNECTION_NAME = 'MongoConnectionName';
5
+ exports.MONGO_MODULE_OPTIONS = 'MongoModuleOptions';
6
+ exports.DEFAULT_MONGO_CONNECTION_NAME = 'DefaultMongo';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Inject the MongoClient object associated with a connection
3
+ * @param connectionName The unique name associated with the connection
4
+ */
5
+ export declare const InjectClient: (connectionName?: string) => PropertyDecorator & ParameterDecorator;
6
+ /**
7
+ * Inject the Mongo Db object associated with a connection
8
+ * @param connectionName The unique name associated with the connection
9
+ */
10
+ export declare const InjectDb: (connectionName?: string) => PropertyDecorator & ParameterDecorator;
11
+ /**
12
+ * Inject the Mongo Collection object associated with a Db
13
+ * @param collectionName The unique name associated with the collection
14
+ */
15
+ export declare const InjectCollection: (collectionName: string) => PropertyDecorator & ParameterDecorator;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InjectCollection = exports.InjectDb = exports.InjectClient = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const mongo_util_1 = require("./mongo.util");
6
+ /**
7
+ * Inject the MongoClient object associated with a connection
8
+ * @param connectionName The unique name associated with the connection
9
+ */
10
+ const InjectClient = (connectionName) => (0, common_1.Inject)((0, mongo_util_1.getClientToken)(connectionName));
11
+ exports.InjectClient = InjectClient;
12
+ /**
13
+ * Inject the Mongo Db object associated with a connection
14
+ * @param connectionName The unique name associated with the connection
15
+ */
16
+ const InjectDb = (connectionName) => (0, common_1.Inject)((0, mongo_util_1.getDbToken)(connectionName));
17
+ exports.InjectDb = InjectDb;
18
+ /**
19
+ * Inject the Mongo Collection object associated with a Db
20
+ * @param collectionName The unique name associated with the collection
21
+ */
22
+ const InjectCollection = (collectionName) => (0, common_1.Inject)((0, mongo_util_1.getCollectionToken)(collectionName));
23
+ exports.InjectCollection = InjectCollection;
@@ -0,0 +1,29 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+ import { MongoModuleAsyncOptions } from './interfaces/mongo-options.interface';
3
+ /**
4
+ * Module for the MongoDB driver
5
+ */
6
+ export declare class MongoModule {
7
+ /**
8
+ * Inject the MongoDB driver synchronously.
9
+ * @param uri The database URI
10
+ * @param dbName The database name
11
+ * @param options Options for the MongoClient that will be created
12
+ * @param connectionName A unique name for the connection. If not specified, a default name
13
+ * will be used.
14
+ */
15
+ static forRoot(uri: string, dbName: string, options?: any, connectionName?: string): DynamicModule;
16
+ /**
17
+ * Inject the MongoDB driver asynchronously, allowing any dependencies such as a configuration
18
+ * service to be injected first.
19
+ * @param options Options for asynchrous injection
20
+ */
21
+ static forRootAsync(options: MongoModuleAsyncOptions): DynamicModule;
22
+ /**
23
+ * Inject collections.
24
+ * @param collections An array of the names of the collections to be injected.
25
+ * @param connectionName A unique name for the connection. If not specified, a default name
26
+ * will be used.
27
+ */
28
+ static forFeature(collections?: string[], connectionName?: string): DynamicModule;
29
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var MongoModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.MongoModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const mongo_providers_1 = require("./mongo.providers");
13
+ const mongo_core_module_1 = require("./mongo-core.module");
14
+ /**
15
+ * Module for the MongoDB driver
16
+ */
17
+ let MongoModule = MongoModule_1 = class MongoModule {
18
+ /**
19
+ * Inject the MongoDB driver synchronously.
20
+ * @param uri The database URI
21
+ * @param dbName The database name
22
+ * @param options Options for the MongoClient that will be created
23
+ * @param connectionName A unique name for the connection. If not specified, a default name
24
+ * will be used.
25
+ */
26
+ static forRoot(uri, dbName, options, connectionName) {
27
+ return {
28
+ module: MongoModule_1,
29
+ imports: [mongo_core_module_1.MongoCoreModule.forRoot(uri, dbName, options, connectionName)]
30
+ };
31
+ }
32
+ /**
33
+ * Inject the MongoDB driver asynchronously, allowing any dependencies such as a configuration
34
+ * service to be injected first.
35
+ * @param options Options for asynchrous injection
36
+ */
37
+ static forRootAsync(options) {
38
+ return {
39
+ module: MongoModule_1,
40
+ imports: [mongo_core_module_1.MongoCoreModule.forRootAsync(options)]
41
+ };
42
+ }
43
+ /**
44
+ * Inject collections.
45
+ * @param collections An array of the names of the collections to be injected.
46
+ * @param connectionName A unique name for the connection. If not specified, a default name
47
+ * will be used.
48
+ */
49
+ static forFeature(collections = [], connectionName) {
50
+ const providers = (0, mongo_providers_1.createMongoProviders)(connectionName, collections);
51
+ return {
52
+ module: MongoModule_1,
53
+ providers: providers,
54
+ exports: providers
55
+ };
56
+ }
57
+ };
58
+ exports.MongoModule = MongoModule;
59
+ exports.MongoModule = MongoModule = MongoModule_1 = __decorate([
60
+ (0, common_1.Module)({})
61
+ ], MongoModule);
@@ -0,0 +1,6 @@
1
+ import { Db } from 'mongodb';
2
+ export declare function createMongoProviders(connectionName?: string, collections?: string[]): {
3
+ provide: string;
4
+ useFactory: (db: Db) => import("mongodb").Collection<import("bson").Document>;
5
+ inject: string[];
6
+ }[];
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMongoProviders = createMongoProviders;
4
+ const mongo_util_1 = require("./mongo.util");
5
+ function createMongoProviders(connectionName, collections = []) {
6
+ return collections.map(collectionName => ({
7
+ provide: (0, mongo_util_1.getCollectionToken)(collectionName),
8
+ useFactory: (db) => db.collection(collectionName),
9
+ inject: [(0, mongo_util_1.getDbToken)(connectionName)]
10
+ }));
11
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Get a token for the MongoClient object for the given connection name
3
+ * @param connectionName The unique name for the connection
4
+ */
5
+ export declare function getClientToken(connectionName?: string): string;
6
+ /**
7
+ * Get a token for the Mongo Db object for the given connection name
8
+ * @param connectionName The unique name for the connection
9
+ */
10
+ export declare function getDbToken(connectionName?: string): string;
11
+ /**
12
+ * Get a token for the Mongo Db object for the given connection name
13
+ * @param collectionName The unique name for the collection
14
+ */
15
+ export declare function getCollectionToken(collectionName: string): string;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getClientToken = getClientToken;
4
+ exports.getDbToken = getDbToken;
5
+ exports.getCollectionToken = getCollectionToken;
6
+ const mongo_constants_1 = require("./mongo.constants");
7
+ /**
8
+ * Get a token for the MongoClient object for the given connection name
9
+ * @param connectionName The unique name for the connection
10
+ */
11
+ function getClientToken(connectionName = mongo_constants_1.DEFAULT_MONGO_CONNECTION_NAME) {
12
+ return `${connectionName}Client`;
13
+ }
14
+ /**
15
+ * Get a token for the Mongo Db object for the given connection name
16
+ * @param connectionName The unique name for the connection
17
+ */
18
+ function getDbToken(connectionName = mongo_constants_1.DEFAULT_MONGO_CONNECTION_NAME) {
19
+ return `${connectionName}Db`;
20
+ }
21
+ /**
22
+ * Get a token for the Mongo Db object for the given connection name
23
+ * @param collectionName The unique name for the collection
24
+ */
25
+ function getCollectionToken(collectionName) {
26
+ return `${collectionName}Collection`;
27
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@sarmorttech/sar-db",
3
+ "version": "1.0.0",
4
+ "description": "A NestJS module for the MongoDB driver",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "scripts": {
8
+ "build": "npm run build:clean && npm run build:tsc",
9
+ "build:clean": "rimraf dist",
10
+ "build:tsc": "tsc",
11
+ "format:check": "prettier --check \"src/**/*.ts\"",
12
+ "format:write": "prettier --write \"src/**/*.ts\""
13
+ },
14
+ "keywords": [
15
+ "mongo",
16
+ "mongodb",
17
+ "nest",
18
+ "nestjs"
19
+ ],
20
+ "author": "Erik Christensen",
21
+ "license": "ISC",
22
+ "devDependencies": {
23
+ "@nestjs/common": "^11.1.19",
24
+ "@nestjs/core": "^11.1.19",
25
+ "@types/node": "^25.6.2",
26
+ "@types/rimraf": "^4.0.5",
27
+ "mongodb": "^7.2.0",
28
+ "prettier": "^3.8.3",
29
+ "reflect-metadata": "^0.2.2",
30
+ "rimraf": "^6.1.3",
31
+ "rxjs": "^7.8.2",
32
+ "typescript": "^6.0.3"
33
+ },
34
+ "peerDependencies": {
35
+ "@nestjs/common": "^11.1.19",
36
+ "@nestjs/core": "^11.1.19",
37
+ "mongodb": "^7.2.0",
38
+ "reflect-metadata": "^0.2.2",
39
+ "rxjs": "^7.8.2"
40
+ }
41
+ }