@abejarano/ts-mongodb-criteria 1.8.2 → 1.8.4

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 CHANGED
@@ -180,11 +180,12 @@ Indexes are created lazily the first time the repository accesses the collection
180
180
  Use the `collection` argument inside `ensureIndexes` to avoid recursion.
181
181
 
182
182
  MongoRepository provides ready-to-use public methods for repositories that extend it:
183
+
183
184
  - `list(criteria, fieldsToExclude?)` for paginated queries
184
185
  - `one(filter)` to fetch a single entity
185
186
  - `upsert(entity)` to persist an aggregate
186
- Internal helpers are private, so repositories should call these public methods
187
- directly.
187
+ Internal helpers are private, so repositories should call these public methods
188
+ directly.
188
189
 
189
190
  If you need a repository interface in your app, extend `IRepository<T>` so your
190
191
  custom interfaces stay aligned with the library return types:
@@ -401,15 +402,16 @@ This will create a `migrate-mongo-config.js` file in your project root. You must
401
402
 
402
403
  ### Commands
403
404
 
404
- | Command | Description |
405
- |---|---|
406
- | `init` | Initialize configuration file |
407
- | `migrate:create <name>` | Create a new migration file |
408
- | `migrate:up` | Run pending migrations |
409
- | `migrate:down` | Revert the last applied migration |
410
- | `migrate:status` | Check the status of migrations |
405
+ | Command | Description |
406
+ | ----------------------- | --------------------------------- |
407
+ | `init` | Initialize configuration file |
408
+ | `migrate:create <name>` | Create a new migration file |
409
+ | `migrate:up` | Run pending migrations |
410
+ | `migrate:down` | Revert the last applied migration |
411
+ | `migrate:status` | Check the status of migrations |
411
412
 
412
413
  Example:
414
+
413
415
  ```bash
414
416
  bun run ts-mongo migrate:create add-users-collection
415
417
  ```
@@ -25,7 +25,7 @@ const validCommands = ["init", "create", "up", "down", "status"];
25
25
  const normalizedCommand = command.replace("migrate:", "");
26
26
  if (!validCommands.includes(normalizedCommand)) {
27
27
  console.error(`Unknown command: ${command}.`);
28
- console.error(`Available commands: ${validCommands.map(c => `migrate:${c}`).join(", ")}`);
28
+ console.error(`Available commands: ${validCommands.map((c) => `migrate:${c}`).join(", ")}`);
29
29
  process.exit(1);
30
30
  }
31
31
  let extraOptions = "";
@@ -27,15 +27,13 @@ class MongoClientFactory {
27
27
  * Crea y conecta una nueva instancia de MongoClient.
28
28
  */
29
29
  static async createAndConnectClient() {
30
- const MONGO_PASS = process.env.MONGO_PASS;
31
- const MONGO_USER = process.env.MONGO_USER;
32
- const MONGO_DB = process.env.MONGO_DB;
33
- const MONGO_SERVER = process.env.MONGO_SERVER;
34
- if (!MONGO_PASS || !MONGO_USER || !MONGO_DB || !MONGO_SERVER) {
35
- throw new Error("Missing MongoDB environment variables.");
30
+ const uri = process.env.MONGO_URI;
31
+ if (!uri) {
32
+ throw new Error("MONGO_URI environment variables are missing to connect to the MongoDB server");
36
33
  }
37
- const uri = `mongodb+srv://${MONGO_USER}:${MONGO_PASS}@${MONGO_SERVER}/${MONGO_DB}?retryWrites=true&w=majority`;
38
- const client = new mongodb_1.MongoClient(uri, { ignoreUndefined: true });
34
+ const client = new mongodb_1.MongoClient(process.env.MONGO_URI, {
35
+ ignoreUndefined: true,
36
+ });
39
37
  try {
40
38
  await client.connect();
41
39
  return client;
@@ -9,23 +9,6 @@ class MongoRepository {
9
9
  this.aggregateRootClass = aggregateRootClass;
10
10
  this.criteriaConverter = new MongoCriteriaConverter_1.MongoCriteriaConverter();
11
11
  }
12
- async ensureIndexesOnce() {
13
- const key = this.collectionName();
14
- if (MongoRepository.indexRegistry.has(key))
15
- return;
16
- const collection = await this.collectionRaw();
17
- await this.ensureIndexes(collection);
18
- MongoRepository.indexRegistry.add(key);
19
- }
20
- async collection() {
21
- await this.ensureIndexesOnce();
22
- return this.collectionRaw();
23
- }
24
- async collectionRaw() {
25
- return (await MongoClientFactory_1.MongoClientFactory.createClient())
26
- .db()
27
- .collection(this.collectionName());
28
- }
29
12
  /** Finds a single entity and hydrates it via the aggregate's fromPrimitives. */
30
13
  async one(filter) {
31
14
  const collection = await this.collection();
@@ -47,12 +30,40 @@ class MongoRepository {
47
30
  const documents = await this.searchByCriteria(criteria, fieldsToExclude);
48
31
  return this.paginate(documents);
49
32
  }
33
+ /**
34
+ * Deletes documents from the database based on a filter and optional options.
35
+ *
36
+ * @param {object} filter - The query to match documents that should be deleted.
37
+ * @param {DeleteOptions} [options] - Optional parameters that modify the behavior of the delete operation.
38
+ * @return {Promise<void>} A promise that resolves when the deletion is complete, or rejects if an error occurs.
39
+ */
40
+ async delete(filter, options) {
41
+ const collection = await this.collection();
42
+ await collection.deleteMany(filter, options);
43
+ }
44
+ async ensureIndexesOnce() {
45
+ const key = this.collectionName();
46
+ if (MongoRepository.indexRegistry.has(key))
47
+ return;
48
+ const collection = await this.collectionRaw();
49
+ await this.ensureIndexes(collection);
50
+ MongoRepository.indexRegistry.add(key);
51
+ }
52
+ async collection() {
53
+ await this.ensureIndexesOnce();
54
+ return this.collectionRaw();
55
+ }
50
56
  async updateOne(filter, update) {
51
57
  const collection = await this.collection();
52
58
  await collection.updateOne(filter, update, {
53
59
  upsert: true,
54
60
  });
55
61
  }
62
+ async collectionRaw() {
63
+ return (await MongoClientFactory_1.MongoClientFactory.createClient())
64
+ .db()
65
+ .collection(this.collectionName());
66
+ }
56
67
  async persist(id, aggregateRoot) {
57
68
  let primitives;
58
69
  if (aggregateRoot.toPrimitives() instanceof Promise) {
@@ -20,7 +20,7 @@ const validCommands = ["init", "create", "up", "down", "status"];
20
20
  const normalizedCommand = command.replace("migrate:", "");
21
21
  if (!validCommands.includes(normalizedCommand)) {
22
22
  console.error(`Unknown command: ${command}.`);
23
- console.error(`Available commands: ${validCommands.map(c => `migrate:${c}`).join(", ")}`);
23
+ console.error(`Available commands: ${validCommands.map((c) => `migrate:${c}`).join(", ")}`);
24
24
  process.exit(1);
25
25
  }
26
26
  let extraOptions = "";
@@ -24,15 +24,13 @@ export class MongoClientFactory {
24
24
  * Crea y conecta una nueva instancia de MongoClient.
25
25
  */
26
26
  static async createAndConnectClient() {
27
- const MONGO_PASS = process.env.MONGO_PASS;
28
- const MONGO_USER = process.env.MONGO_USER;
29
- const MONGO_DB = process.env.MONGO_DB;
30
- const MONGO_SERVER = process.env.MONGO_SERVER;
31
- if (!MONGO_PASS || !MONGO_USER || !MONGO_DB || !MONGO_SERVER) {
32
- throw new Error("Missing MongoDB environment variables.");
27
+ const uri = process.env.MONGO_URI;
28
+ if (!uri) {
29
+ throw new Error("MONGO_URI environment variables are missing to connect to the MongoDB server");
33
30
  }
34
- const uri = `mongodb+srv://${MONGO_USER}:${MONGO_PASS}@${MONGO_SERVER}/${MONGO_DB}?retryWrites=true&w=majority`;
35
- const client = new MongoClient(uri, { ignoreUndefined: true });
31
+ const client = new MongoClient(process.env.MONGO_URI, {
32
+ ignoreUndefined: true,
33
+ });
36
34
  try {
37
35
  await client.connect();
38
36
  return client;
@@ -1,28 +1,11 @@
1
1
  import { MongoCriteriaConverter } from "./MongoCriteriaConverter";
2
2
  import { MongoClientFactory } from "./MongoClientFactory";
3
- import { ObjectId } from "mongodb";
3
+ import { ObjectId, } from "mongodb";
4
4
  export class MongoRepository {
5
5
  constructor(aggregateRootClass) {
6
6
  this.aggregateRootClass = aggregateRootClass;
7
7
  this.criteriaConverter = new MongoCriteriaConverter();
8
8
  }
9
- async ensureIndexesOnce() {
10
- const key = this.collectionName();
11
- if (MongoRepository.indexRegistry.has(key))
12
- return;
13
- const collection = await this.collectionRaw();
14
- await this.ensureIndexes(collection);
15
- MongoRepository.indexRegistry.add(key);
16
- }
17
- async collection() {
18
- await this.ensureIndexesOnce();
19
- return this.collectionRaw();
20
- }
21
- async collectionRaw() {
22
- return (await MongoClientFactory.createClient())
23
- .db()
24
- .collection(this.collectionName());
25
- }
26
9
  /** Finds a single entity and hydrates it via the aggregate's fromPrimitives. */
27
10
  async one(filter) {
28
11
  const collection = await this.collection();
@@ -44,12 +27,40 @@ export class MongoRepository {
44
27
  const documents = await this.searchByCriteria(criteria, fieldsToExclude);
45
28
  return this.paginate(documents);
46
29
  }
30
+ /**
31
+ * Deletes documents from the database based on a filter and optional options.
32
+ *
33
+ * @param {object} filter - The query to match documents that should be deleted.
34
+ * @param {DeleteOptions} [options] - Optional parameters that modify the behavior of the delete operation.
35
+ * @return {Promise<void>} A promise that resolves when the deletion is complete, or rejects if an error occurs.
36
+ */
37
+ async delete(filter, options) {
38
+ const collection = await this.collection();
39
+ await collection.deleteMany(filter, options);
40
+ }
41
+ async ensureIndexesOnce() {
42
+ const key = this.collectionName();
43
+ if (MongoRepository.indexRegistry.has(key))
44
+ return;
45
+ const collection = await this.collectionRaw();
46
+ await this.ensureIndexes(collection);
47
+ MongoRepository.indexRegistry.add(key);
48
+ }
49
+ async collection() {
50
+ await this.ensureIndexesOnce();
51
+ return this.collectionRaw();
52
+ }
47
53
  async updateOne(filter, update) {
48
54
  const collection = await this.collection();
49
55
  await collection.updateOne(filter, update, {
50
56
  upsert: true,
51
57
  });
52
58
  }
59
+ async collectionRaw() {
60
+ return (await MongoClientFactory.createClient())
61
+ .db()
62
+ .collection(this.collectionName());
63
+ }
53
64
  async persist(id, aggregateRoot) {
54
65
  let primitives;
55
66
  if (aggregateRoot.toPrimitives() instanceof Promise) {
@@ -1,7 +1,9 @@
1
1
  import { Criteria, Paginate } from "../criteria";
2
2
  import { AggregateRoot } from "../AggregateRoot";
3
+ import { DeleteOptions } from "mongodb";
3
4
  export interface IRepository<T extends AggregateRoot> {
4
5
  one(filter: object): Promise<T | null>;
5
6
  list<D>(criteria: Criteria, fieldsToExclude?: string[]): Promise<Paginate<D>>;
6
7
  upsert(entity: T): Promise<void>;
8
+ delete(filter: object, options?: DeleteOptions): Promise<void>;
7
9
  }
@@ -1,25 +1,33 @@
1
1
  import { Criteria, Paginate } from "../criteria";
2
2
  import { AggregateRoot, AggregateRootClass } from "../AggregateRoot";
3
- import { Collection, Document, UpdateFilter } from "mongodb";
3
+ import { Collection, DeleteOptions, Document, UpdateFilter } from "mongodb";
4
4
  export declare abstract class MongoRepository<T extends AggregateRoot> {
5
5
  private readonly aggregateRootClass;
6
+ private static indexRegistry;
6
7
  private criteriaConverter;
7
8
  private query;
8
9
  private criteria;
9
- private static indexRegistry;
10
10
  protected constructor(aggregateRootClass: AggregateRootClass<T>);
11
11
  abstract collectionName(): string;
12
- protected abstract ensureIndexes(collection: Collection): Promise<void>;
13
- protected ensureIndexesOnce(): Promise<void>;
14
- protected collection<U extends Document>(): Promise<Collection<U>>;
15
- private collectionRaw;
16
12
  /** Finds a single entity and hydrates it via the aggregate's fromPrimitives. */
17
13
  one(filter: object): Promise<T | null>;
18
14
  /** Upserts an aggregate by delegating to persist with its id. */
19
15
  upsert(entity: T): Promise<void>;
20
16
  /** Lists entities by criteria and returns a paginated response. */
21
17
  list<D>(criteria: Criteria, fieldsToExclude?: string[]): Promise<Paginate<D>>;
18
+ /**
19
+ * Deletes documents from the database based on a filter and optional options.
20
+ *
21
+ * @param {object} filter - The query to match documents that should be deleted.
22
+ * @param {DeleteOptions} [options] - Optional parameters that modify the behavior of the delete operation.
23
+ * @return {Promise<void>} A promise that resolves when the deletion is complete, or rejects if an error occurs.
24
+ */
25
+ delete(filter: object, options?: DeleteOptions): Promise<void>;
26
+ protected abstract ensureIndexes(collection: Collection): Promise<void>;
27
+ protected ensureIndexesOnce(): Promise<void>;
28
+ protected collection<U extends Document>(): Promise<Collection<U>>;
22
29
  protected updateOne(filter: object, update: Document[] | UpdateFilter<any>): Promise<void>;
30
+ private collectionRaw;
23
31
  private persist;
24
32
  private searchByCriteria;
25
33
  private paginate;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@abejarano/ts-mongodb-criteria",
3
3
  "author": "angel bejarano / angel.bejarano@jaspesoft.com",
4
- "version": "1.8.2",
4
+ "version": "1.8.4",
5
5
  "description": "Patrón Criteria para consultas MongoDB en TypeScript",
6
6
  "main": "dist/cjs/index.js",
7
7
  "module": "dist/esm/index.js",
@@ -63,7 +63,7 @@
63
63
  "@types/node": "^24.5.2",
64
64
  "jest": "^29.7.0",
65
65
  "mongodb": "^7.0.0",
66
- "prettier": "^3.7.4",
66
+ "prettier": "^3.8.3",
67
67
  "rimraf": "^6.1.2",
68
68
  "semantic-release": "^24.2.9",
69
69
  "ts-jest": "^29.1.2",