Skip to content

fix: make mongodb import lazy in casbinMongoRule (type-only import)#82

Open
JohannesWill wants to merge 1 commit into
apache:masterfrom
JohannesWill:fix/lazy-mongodb-import
Open

fix: make mongodb import lazy in casbinMongoRule (type-only import)#82
JohannesWill wants to merge 1 commit into
apache:masterfrom
JohannesWill:fix/lazy-mongodb-import

Conversation

@JohannesWill

Copy link
Copy Markdown

Problem

Since 1.10.0, importing typeorm-adapter throws Cannot find module 'mongodb' (MODULE_NOT_FOUND) for any consumer that does not have mongodb installed — even when using a different driver (PostgreSQL, SQLite, …).

src/index.ts re-exports casbinMongoRule, and src/casbinMongoRule.ts imports mongodb at the top level. mongodb is only an optional peer dependency of typeorm and merely a devDependency here, so it is absent in most production installs.

Fix

ObjectId is only used as a type (public id!: ObjectId;). Switching to a type-only import removes the runtime require('mongodb'): with emitDecoratorMetadata, TypeScript no longer emits a reference to mongodb.ObjectId.

-import { ObjectId } from 'mongodb';
+import type { ObjectId } from 'mongodb';

Verification

Compiled output no longer contains any reference to mongodb:

__decorate([
    ObjectIdColumn(),
    __metadata("design:type", Function)
], CasbinMongoRule.prototype, "id", void 0);

grep -c mongodb lib/casbinMongoRule.js0. Build (tsc) and lint pass.

MongoDB users are unaffected — TypeORM loads the mongodb driver lazily via its own PlatformTools when a Mongo DataSource is actually initialized.

Closes #81

Use a type-only import for `ObjectId` in casbinMongoRule so importing
the package no longer emits a top-level `require('mongodb')`. mongodb is
only an optional peer dependency of typeorm and is used solely as a type
here, so non-MongoDB consumers were crashing at import time with
MODULE_NOT_FOUND. With `import type`, no runtime reference to mongodb is
emitted. MongoDB users are unaffected since typeorm loads the driver
lazily when a Mongo DataSource is initialized.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

v1.10.0: hard import 'mongodb' in casbinMongoRule breaks all non-MongoDB users (MODULE_NOT_FOUND)

2 participants