@edirect/mongo 11.0.60 → 11.0.61

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/package.json CHANGED
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "name": "@edirect/mongo",
3
- "version": "11.0.60",
4
- "packageScope": "@edirect",
3
+ "version": "11.0.61",
5
4
  "main": "./dist/src/index.js",
6
5
  "types": "./dist/src/index.d.ts",
7
6
  "exports": {
@@ -18,27 +17,11 @@
18
17
  ],
19
18
  "dependencies": {
20
19
  "@aws-sdk/credential-providers": "^3.1045.0",
20
+ "@edirect/config": "^11.0.61",
21
21
  "@nestjs/common": "^11.1.19",
22
22
  "mongodb": "^7.2.0",
23
23
  "mongoose": "^9.6.2",
24
- "tslib": "^2.8.1",
25
- "@edirect/config": "11.0.60"
24
+ "tslib": "^2.8.1"
26
25
  },
27
- "nx": {
28
- "name": "@edirect/mongo",
29
- "targets": {
30
- "build": {
31
- "executor": "@nx/js:tsc",
32
- "options": {
33
- "main": "{workspaceRoot}/packages/edirect-mongo/src/index.ts",
34
- "tsConfig": "{workspaceRoot}/packages/edirect-mongo/tsconfig.lib.json",
35
- "outputPath": "{workspaceRoot}/packages/edirect-mongo/dist",
36
- "assets": [
37
- "{workspaceRoot}/packages/edirect-mongo/package.json",
38
- "{workspaceRoot}/packages/edirect-mongo/README.md"
39
- ]
40
- }
41
- }
42
- }
43
- }
44
- }
26
+ "type": "commonjs"
27
+ }
package/dist/README.md DELETED
@@ -1,249 +0,0 @@
1
- # @edirect/mongo
2
-
3
- > NestJS global module for MongoDB connections with Mongoose, including AWS IAM (IRSA) authentication support.
4
-
5
- This package provides a plug-and-play NestJS module that manages a Mongoose connection to MongoDB. It reads connection configuration from the environment via `@edirect/config`, automatically applies AWS IAM credential rotation when the `MONGODB-AWS` auth mechanism is detected, and tunes connection-pool settings for non-production environments. The resulting `Mongoose` instance is exposed under the `MONGO_CONNECTION` injection token and is available globally across the application.
6
-
7
- ## Features
8
-
9
- - Single-import global NestJS module (`MongoModule`)
10
- - Automatic AWS IAM / IRSA credential rotation via `@aws-sdk/credential-providers`
11
- - Supports both `MONGO_URL` and `MONGODB_URI` environment variables (priority: `MONGO_URL`)
12
- - Conservative connection-pool defaults for development and test environments
13
- - `getConnection` utility for building connection parameters outside NestJS DI
14
- - `MONGO_CONNECTION` injection token for direct `Mongoose` instance injection
15
-
16
- ## Installation
17
-
18
- ```bash
19
- npm install @edirect/mongo
20
- ```
21
-
22
- ## Configuration
23
-
24
- ### Environment Variables
25
-
26
- | Variable | Type | Default | Description |
27
- | ----------------------------- | -------- | ------- | ---------------------------------------------------------------------------------- |
28
- | `MONGO_URL` | `string` | — | Primary MongoDB connection string (takes precedence over `MONGODB_URI`). |
29
- | `MONGODB_URI` | `string` | — | Fallback MongoDB connection string. |
30
- | `NODE_ENV` | `string` | — | Runtime environment. When `production` or `live`, pool tuning is disabled. |
31
- | `MONGODB_AWS_ROLE_ARN` | `string` | — | **AWS IAM auth only.** ARN of the IAM role to assume via STS. |
32
- | `AWS_WEB_IDENTITY_TOKEN_FILE` | `string` | — | **AWS IAM auth only.** Path to the Kubernetes service-account token file for IRSA. |
33
-
34
- > At least one of `MONGO_URL` or `MONGODB_URI` must be set, or the module will throw at startup.
35
-
36
- ## Usage
37
-
38
- ### Basic Setup
39
-
40
- ```typescript
41
- // app.module.ts
42
- import { Module } from '@nestjs/common';
43
- import { MongoModule } from '@edirect/mongo';
44
-
45
- @Module({
46
- imports: [MongoModule],
47
- })
48
- export class AppModule {}
49
- ```
50
-
51
- ### Injecting the Mongoose Connection
52
-
53
- Use the `MONGO_CONNECTION` token to inject the raw Mongoose instance anywhere in your application:
54
-
55
- ```typescript
56
- import { Injectable, Inject } from '@nestjs/common';
57
- import { MONGO_CONNECTION } from '@edirect/mongo';
58
- import mongoose from 'mongoose';
59
-
60
- @Injectable()
61
- export class DatabaseService {
62
- constructor(
63
- @Inject(MONGO_CONNECTION) private readonly connection: mongoose.Mongoose
64
- ) {}
65
-
66
- isConnected(): boolean {
67
- return this.connection.connection.readyState === 1;
68
- }
69
- }
70
- ```
71
-
72
- ### Registering Mongoose Models
73
-
74
- After importing `MongoModule`, register your schemas as model providers in feature modules:
75
-
76
- ```typescript
77
- import { Module } from '@nestjs/common';
78
- import { getModelToken } from 'mongoose';
79
- import { MONGO_CONNECTION } from '@edirect/mongo';
80
- import { PolicySchema } from './policy.schema';
81
-
82
- @Module({
83
- providers: [
84
- {
85
- provide: getModelToken('Policy'),
86
- useFactory: (connection: mongoose.Mongoose) =>
87
- connection.model('Policy', PolicySchema),
88
- inject: [MONGO_CONNECTION],
89
- },
90
- ],
91
- exports: [getModelToken('Policy')],
92
- })
93
- export class PolicyModule {}
94
- ```
95
-
96
- ### Standard Username/Password Connection
97
-
98
- ```dotenv
99
- # .production.env
100
- MONGO_URL=mongodb://username:password@mongo-host:27017/mydb?authSource=admin
101
- ```
102
-
103
- ### AWS IAM (IRSA/EKS) Connection
104
-
105
- For EKS workloads with IRSA enabled, set the following environment variables:
106
-
107
- ```dotenv
108
- MONGO_URL=mongodb+srv://cluster.example.com/mydb?authMechanism=MONGODB-AWS
109
- MONGODB_AWS_ROLE_ARN=arn:aws:iam::123456789012:role/my-mongo-role
110
- AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token
111
- ```
112
-
113
- The module will automatically rotate credentials using `@aws-sdk/credential-providers` `fromNodeProviderChain`.
114
-
115
- ### Using `getConnection` Programmatically
116
-
117
- ```typescript
118
- import { getConnection } from '@edirect/mongo';
119
- import { ConfigService } from '@edirect/config';
120
-
121
- const config = new ConfigService();
122
- const connectionParams = getConnection(config);
123
- // Returns mongoose connection parameters object
124
-
125
- const connection = await mongoose.createConnection(
126
- connectionParams.uri,
127
- connectionParams.options
128
- );
129
- ```
130
-
131
- ### Connection Pool Sizing
132
-
133
- The module automatically adjusts pool settings based on `NODE_ENV`:
134
-
135
- | `NODE_ENV` | Behavior |
136
- | --------------------- | ---------------------------------------------------- |
137
- | `production` / `live` | Default Mongoose pool settings |
138
- | anything else | Conservative pool settings (reduced for development) |
139
-
140
- ## API Reference
141
-
142
- ### `MongoModule`
143
-
144
- A global `@Module()` with no configuration options. Import it once in your root `AppModule`.
145
-
146
- ```typescript
147
- import { MongoModule } from '@edirect/mongo';
148
- ```
149
-
150
- ### `getConnection(configService: ConfigService): MongoConnectionParams`
151
-
152
- Utility function that resolves the MongoDB connection string from `ConfigService` and returns the connection parameters.
153
-
154
- | Parameter | Type | Description |
155
- | --------------- | --------------- | ----------------------------------------------- |
156
- | `configService` | `ConfigService` | Instance of `@edirect/config`'s `ConfigService` |
157
-
158
- **Returns:** Object containing the resolved URI and Mongoose connection options.
159
-
160
- **Throws:** If neither `MONGO_URL` nor `MONGODB_URI` is set in the environment.
161
-
162
- ### `MONGO_CONNECTION`
163
-
164
- Injection token (`string`) for the Mongoose instance. Use with `@Inject(MONGO_CONNECTION)`.
165
-
166
- ### `MongoProviders`
167
-
168
- Array of NestJS providers that wires the `MONGO_CONNECTION` token. Used internally by `MongoModule`.
169
-
170
- ## Examples
171
-
172
- ### Complete AppModule with Mongoose Model
173
-
174
- ```typescript
175
- // app.module.ts
176
- import { Module } from '@nestjs/common';
177
- import { MongoModule } from '@edirect/mongo';
178
- import { PolicyModule } from './policy/policy.module';
179
-
180
- @Module({
181
- imports: [MongoModule, PolicyModule],
182
- })
183
- export class AppModule {}
184
- ```
185
-
186
- ```typescript
187
- // policy/policy.module.ts
188
- import { Module } from '@nestjs/common';
189
- import mongoose, { Schema } from 'mongoose';
190
- import { MONGO_CONNECTION } from '@edirect/mongo';
191
- import { PolicyService } from './policy.service';
192
-
193
- const PolicySchema = new Schema({
194
- policyNumber: String,
195
- premium: Number,
196
- startDate: Date,
197
- });
198
-
199
- @Module({
200
- providers: [
201
- {
202
- provide: 'POLICY_MODEL',
203
- useFactory: (conn: mongoose.Mongoose) =>
204
- conn.model('Policy', PolicySchema),
205
- inject: [MONGO_CONNECTION],
206
- },
207
- PolicyService,
208
- ],
209
- exports: [PolicyService],
210
- })
211
- export class PolicyModule {}
212
- ```
213
-
214
- ```typescript
215
- // policy/policy.service.ts
216
- import { Injectable, Inject } from '@nestjs/common';
217
- import { Model } from 'mongoose';
218
-
219
- @Injectable()
220
- export class PolicyService {
221
- constructor(
222
- @Inject('POLICY_MODEL') private readonly policyModel: Model<any>
223
- ) {}
224
-
225
- findAll() {
226
- return this.policyModel.find().exec();
227
- }
228
- }
229
- ```
230
-
231
- ### Health Check
232
-
233
- ```typescript
234
- import { Injectable, Inject } from '@nestjs/common';
235
- import { MONGO_CONNECTION } from '@edirect/mongo';
236
- import mongoose from 'mongoose';
237
-
238
- @Injectable()
239
- export class HealthService {
240
- constructor(
241
- @Inject(MONGO_CONNECTION) private readonly mongo: mongoose.Mongoose
242
- ) {}
243
-
244
- isHealthy(): boolean {
245
- // readyState: 0=disconnected, 1=connected, 2=connecting, 3=disconnecting
246
- return this.mongo.connection.readyState === 1;
247
- }
248
- }
249
- ```
package/dist/package.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "name": "@edirect/mongo",
3
- "version": "11.0.59",
4
- "main": "./dist/src/index.js",
5
- "types": "./dist/src/index.d.ts",
6
- "exports": {
7
- ".": {
8
- "import": "./dist/src/index.js",
9
- "default": "./dist/src/index.js",
10
- "require": "./dist/src/index.js",
11
- "types": "./dist/src/index.d.ts"
12
- },
13
- "./package.json": "./package.json"
14
- },
15
- "files": [
16
- "dist"
17
- ],
18
- "dependencies": {
19
- "@aws-sdk/credential-providers": "^3.1045.0",
20
- "@edirect/config": "^11.0.59",
21
- "@nestjs/common": "^11.1.19",
22
- "mongodb": "^7.2.0",
23
- "mongoose": "^9.6.2",
24
- "tslib": "^2.8.1"
25
- },
26
- "type": "commonjs"
27
- }
package/dist/src/aws.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import { AWSCredentials } from 'mongodb';
2
- export declare const MONGODB_AWS_ROLE_ARN: string | undefined;
3
- export declare const AWS_WEB_IDENTITY_TOKEN_FILE: string | undefined;
4
- export declare function getMongoAwsCredentialProvider(): () => Promise<AWSCredentials>;
5
- //# sourceMappingURL=aws.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"aws.d.ts","sourceRoot":"","sources":["../../src/aws.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAKzC,eAAO,MAAM,oBAAoB,oBAAmC,CAAC;AACrE,eAAO,MAAM,2BAA2B,oBACC,CAAC;AAI1C,wBAAgB,6BAA6B,IAAI,MAAM,OAAO,CAAC,cAAc,CAAC,CAY7E"}
package/dist/src/aws.js DELETED
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AWS_WEB_IDENTITY_TOKEN_FILE = exports.MONGODB_AWS_ROLE_ARN = void 0;
4
- exports.getMongoAwsCredentialProvider = getMongoAwsCredentialProvider;
5
- const credential_providers_1 = require("@aws-sdk/credential-providers");
6
- // Environment variables required for IRSA/EKS role assumption authentication:
7
- // MONGODB_AWS_ROLE_ARN: the AWS IAM Role ARN to assume
8
- // AWS_WEB_IDENTITY_TOKEN_FILE: path to serviceAccount token (set by kubelet when IRSA is enabled)
9
- exports.MONGODB_AWS_ROLE_ARN = process.env.MONGODB_AWS_ROLE_ARN;
10
- exports.AWS_WEB_IDENTITY_TOKEN_FILE = process.env.AWS_WEB_IDENTITY_TOKEN_FILE;
11
- // A dynamic credentials provider for the MongoDB driver that will always fetch fresh AWS credentials (using IRSA+STS)
12
- // ALWAYS use this as the value of AWS_CREDENTIAL_PROVIDER in authMechanismProperties. Never embed static keys/tokens in the URI.
13
- function getMongoAwsCredentialProvider() {
14
- if (!exports.MONGODB_AWS_ROLE_ARN || !exports.AWS_WEB_IDENTITY_TOKEN_FILE) {
15
- throw new Error('[mongo] MONGODB_AWS_ROLE_ARN or AWS_WEB_IDENTITY_TOKEN_FILE are not set. ' +
16
- 'These are required for AWS IAM auth (IRSA, STS assume role), and must be set in the environment!');
17
- }
18
- // This permanently produces a rotating credentials chain using the specified roleArn, IRSA, and web identity token
19
- const credentialChain = (0, credential_providers_1.fromNodeProviderChain)({
20
- roleArn: exports.MONGODB_AWS_ROLE_ARN,
21
- });
22
- return () => credentialChain();
23
- }
@@ -1,3 +0,0 @@
1
- export * from './mongo.module';
2
- export { getConnection } from './mongo.providers';
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/src/index.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getConnection = void 0;
4
- const tslib_1 = require("tslib");
5
- tslib_1.__exportStar(require("./mongo.module"), exports);
6
- var mongo_providers_1 = require("./mongo.providers");
7
- Object.defineProperty(exports, "getConnection", { enumerable: true, get: function () { return mongo_providers_1.getConnection; } });
@@ -1,3 +0,0 @@
1
- export declare class MongoModule {
2
- }
3
- //# sourceMappingURL=mongo.module.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mongo.module.d.ts","sourceRoot":"","sources":["../../src/mongo.module.ts"],"names":[],"mappings":"AAKA,qBAMa,WAAW;CAAG"}
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoModule = void 0;
4
- const tslib_1 = require("tslib");
5
- const config_1 = require("@edirect/config");
6
- const common_1 = require("@nestjs/common");
7
- const mongo_providers_1 = require("./mongo.providers");
8
- let MongoModule = class MongoModule {
9
- };
10
- exports.MongoModule = MongoModule;
11
- exports.MongoModule = MongoModule = tslib_1.__decorate([
12
- (0, common_1.Global)(),
13
- (0, common_1.Module)({
14
- imports: [config_1.ConfigModule],
15
- providers: [...mongo_providers_1.MongoProviders],
16
- exports: [...mongo_providers_1.MongoProviders],
17
- })
18
- ], MongoModule);
@@ -1,9 +0,0 @@
1
- import { ConnectOptions } from 'mongoose';
2
- import { Provider } from '@nestjs/common';
3
- import { ConfigService } from '@edirect/config';
4
- export declare function getConnection(configService: ConfigService): Promise<{
5
- uri: string;
6
- options: ConnectOptions;
7
- }>;
8
- export declare const MongoProviders: Provider[];
9
- //# sourceMappingURL=mongo.providers.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mongo.providers.d.ts","sourceRoot":"","sources":["../../src/mongo.providers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,cAAc,EAAY,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAsB,aAAa,EAAE,MAAM,iBAAiB,CAAC;AASpE,wBAAsB,aAAa,CAAC,aAAa,EAAE,aAAa;;;GAmB/D;AAED,eAAO,MAAM,cAAc,EAAE,QAAQ,EAcpC,CAAC"}
@@ -1,44 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoProviders = void 0;
4
- exports.getConnection = getConnection;
5
- const mongoose_1 = require("mongoose");
6
- const config_1 = require("@edirect/config");
7
- const aws_1 = require("./aws");
8
- const isNotProductionOrLive = (nodeEnv) => nodeEnv !== 'production' && nodeEnv !== 'live';
9
- const mongoUrl = (configService) => configService.get('MONGO_URL') ?? configService.get('MONGODB_URI');
10
- async function getConnection(configService) {
11
- const connectionString = mongoUrl(configService);
12
- if (!connectionString)
13
- throw new config_1.ConfigMissingError('MONGO_URL');
14
- const options = {};
15
- // Always use dynamic AWS credential provider for MongoDB-AWS mechanism
16
- if ((connectionString ?? '').includes('MONGODB-AWS')) {
17
- options.authMechanismProperties = {
18
- // This will provide rotating, always-fresh AWS credentials via IRSA
19
- AWS_CREDENTIAL_PROVIDER: (0, aws_1.getMongoAwsCredentialProvider)(),
20
- };
21
- }
22
- // Pool sizing for dev/test only
23
- if (isNotProductionOrLive(configService.get('NODE_ENV'))) {
24
- options.minPoolSize = 0;
25
- options.maxPoolSize = 10;
26
- }
27
- return { uri: connectionString, options };
28
- }
29
- exports.MongoProviders = [
30
- {
31
- provide: 'MONGO_CONNECTION',
32
- useFactory: async (configService) => {
33
- const { uri, options } = await getConnection(configService);
34
- try {
35
- return await (0, mongoose_1.connect)(uri, options);
36
- }
37
- catch (err) {
38
- console.error('[mongo] Failed to connect to MongoDB:', err);
39
- throw err;
40
- }
41
- },
42
- inject: [config_1.ConfigService],
43
- },
44
- ];
@@ -1 +0,0 @@
1
- {"version":"5.9.3"}