@medyll/idae-db 0.13.0 → 0.25.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 CHANGED
@@ -1,5 +1,170 @@
1
+ # Idae Database Library
1
2
 
2
- ```json
3
- "description": "@medyll/idae-db is a flexible and powerful library for interacting with various databases, with a particular focus on MongoDB support. It offers robust connection management, an intuitive API, and simplified CRUD operations."
3
+ The Idae Database Library provides a flexible and extensible way to interact with various databases such as MongoDB, MySQL, and ChromaDB. It includes features like event emitters for pre/post hooks, auto-increment fields, and more.
4
+
5
+ ## Installation
6
+
7
+ To install the library, run:
8
+
9
+ ```bash
10
+ npm install idae-db
4
11
  ```
5
12
 
13
+ ## Usage
14
+
15
+ ### Initialization
16
+
17
+ First, initialize the database connection:
18
+
19
+ #### MongoDB
20
+
21
+ ```typescript
22
+ import { IdaeDb } from './lib/idaeDb.js';
23
+ import { DbType } from './lib/@types/types.js';
24
+
25
+ const mongoDb = IdaeDb.init('mongodb://localhost:27017', {
26
+ dbType: DbType.MONGODB,
27
+ dbScope: 'a_idae_db_sitebase',
28
+ dbScopeSeparator: '_',
29
+ idaeModelOptions: {
30
+ autoIncrementFormat: (collection: string) => `id${collection}`,
31
+ autoIncrementDbCollection: 'auto_increment'
32
+ }
33
+ });
34
+ ```
35
+
36
+ #### MySQL
37
+
38
+ ```typescript
39
+ import { IdaeDb } from './lib/idaeDb.js';
40
+ import { DbType } from './lib/@types/types.js';
41
+
42
+ const mysqlDb = IdaeDb.init('mysql://user:password@localhost:3306', {
43
+ dbType: DbType.MYSQL,
44
+ dbScope: 'a_idae_db_sitebase',
45
+ dbScopeSeparator: '_',
46
+ idaeModelOptions: {
47
+ autoIncrementFormat: (collection: string) => `id${collection}`,
48
+ autoIncrementDbCollection: 'auto_increment'
49
+ }
50
+ });
51
+ ```
52
+
53
+ ### Create a Connection
54
+
55
+ Create a connection to the database:
56
+
57
+ ```typescript
58
+ await mongoDb.db('app');
59
+ await mysqlDb.db('app');
60
+ ```
61
+
62
+ ### Define a Model
63
+
64
+ Define a model interface:
65
+
66
+ ```typescript
67
+ interface User {
68
+ iduser: number;
69
+ name: string;
70
+ email: string;
71
+ age: number;
72
+ }
73
+ ```
74
+
75
+ ### Register Event Listeners
76
+
77
+ Register event listeners for various operations:
78
+
79
+ ```typescript
80
+ const usersCollection = mongoDb.collection<User>('user');
81
+
82
+ usersCollection.registerEvents<any>({
83
+ findById: {
84
+ pre: (id) => console.log(`About to find document with id: ${id}`),
85
+ post: (result, id) => console.log(`Found document for id ${id}:`, result),
86
+ error: (error) => console.error('Error in findById:', error)
87
+ },
88
+ update: {
89
+ pre: (id, data) => console.log(`About to update document ${id} with:`, data),
90
+ post: (result, id, data) => console.log(`Updated document ${id}:`, result)
91
+ },
92
+ create: {
93
+ pre: (data) => console.log(`About to create document with:`, data),
94
+ post: (data, result) => console.log(`Created document `, data, result)
95
+ }
96
+ });
97
+ ```
98
+
99
+ ### CRUD Operations
100
+
101
+ Perform CRUD operations:
102
+
103
+ #### MongoDB
104
+
105
+ ```typescript
106
+ // Create a new user
107
+ const newUser = await usersCollection.create({
108
+ name: 'John Doe',
109
+ email: 'john@example.com',
110
+ age: 30
111
+ });
112
+
113
+ // Find a user by email
114
+ const user = await usersCollection.findOne({ query: { email: 'john@example.com' } });
115
+
116
+ // Update a user's age
117
+ const updateResult = await usersCollection.update(user.iduser, { age: 31 });
118
+
119
+ // Find users with age greater than 25
120
+ const users = await usersCollection.find({
121
+ query: { age: { $gt: 25 } },
122
+ sortBy: 'name:asc',
123
+ limit: 10
124
+ });
125
+
126
+ // Delete a user by ID
127
+ const deleteResult = await usersCollection.deleteById(5);
128
+ ```
129
+
130
+ #### MySQL
131
+
132
+ ```typescript
133
+ const usersCollection = mysqlDb.collection<User>('user');
134
+
135
+ // Create a new user
136
+ const newUser = await usersCollection.create({
137
+ name: 'John Doe',
138
+ email: 'john@example.com',
139
+ age: 30
140
+ });
141
+
142
+ // Find a user by email
143
+ const user = await usersCollection.findOne({ query: { email: 'john@example.com' } });
144
+
145
+ // Update a user's age
146
+ const updateResult = await usersCollection.update(user.iduser, { age: 31 });
147
+
148
+ // Find users with age greater than 25
149
+ const users = await usersCollection.find({
150
+ query: { age: { $gt: 25 } },
151
+ sortBy: 'name:asc',
152
+ limit: 10
153
+ });
154
+
155
+ // Delete a user by ID
156
+ const deleteResult = await usersCollection.deleteById(5);
157
+ ```
158
+
159
+ ### Close Connections
160
+
161
+ Close all connections when done:
162
+
163
+ ```typescript
164
+ await mongoDb.closeAllConnections();
165
+ await mysqlDb.closeAllConnections();
166
+ ```
167
+
168
+ ## License
169
+
170
+ This project is licensed under the MIT License.
@@ -4,6 +4,9 @@ export interface IdaeModelOptions {
4
4
  autoIncrementFormat?: (collection: string) => string;
5
5
  autoIncrementDbCollection?: string;
6
6
  }
7
+ /**
8
+ * Models are attached to a connection.
9
+ */
7
10
  export declare class IdaeDBModel<T extends object> {
8
11
  private connection;
9
12
  private _collectionName;
@@ -11,9 +14,19 @@ export declare class IdaeDBModel<T extends object> {
11
14
  private _autoIncrementField;
12
15
  private _autoIncrementDbCollection;
13
16
  private _fieldId;
17
+ /**
18
+ * Creates an instance of IdaeDBModel.
19
+ * @param connection The database connection.
20
+ * @param _collectionName The name of the collection.
21
+ * @param options Optional model options.
22
+ */
14
23
  constructor(connection: IdaeDbConnection, _collectionName: string, options?: Partial<IdaeModelOptions>);
15
24
  get collection(): Collection<T>;
16
25
  get collectionName(): string;
17
26
  get fieldId(): string;
27
+ /**
28
+ * Gets the next auto-increment value.
29
+ * @returns The next increment value.
30
+ */
18
31
  getNextIncrement(): Promise<any>;
19
32
  }
@@ -1,6 +1,8 @@
1
1
  import { IdaeDbConnection } from './IdaeDbConnection.js';
2
2
  import { IdaeDb } from './idaeDb.js';
3
- // models are attached to a connection
3
+ /**
4
+ * Models are attached to a connection.
5
+ */
4
6
  export class IdaeDBModel {
5
7
  connection;
6
8
  _collectionName;
@@ -8,6 +10,12 @@ export class IdaeDBModel {
8
10
  _autoIncrementField = undefined;
9
11
  _autoIncrementDbCollection = undefined;
10
12
  _fieldId = '_id';
13
+ /**
14
+ * Creates an instance of IdaeDBModel.
15
+ * @param connection The database connection.
16
+ * @param _collectionName The name of the collection.
17
+ * @param options Optional model options.
18
+ */
11
19
  constructor(connection, _collectionName, options) {
12
20
  this.connection = connection;
13
21
  this._collectionName = _collectionName;
@@ -25,6 +33,10 @@ export class IdaeDBModel {
25
33
  get fieldId() {
26
34
  return this._fieldId;
27
35
  }
36
+ /**
37
+ * Gets the next auto-increment value.
38
+ * @returns The next increment value.
39
+ */
28
40
  async getNextIncrement() {
29
41
  const idaeAuto = IdaeDb.init(this.connection.idaeDb.uri, this.connection.idaeDb.options);
30
42
  const increment_name = 'increment';
@@ -8,6 +8,9 @@ export type EventListeners<T extends object> = {
8
8
  error?: ErrorEventListener;
9
9
  };
10
10
  };
11
+ /**
12
+ * IdaeDbAdapter class that extends IdaeEventEmitter and implements AbstractIdaeDbAdapter.
13
+ */
11
14
  export declare class IdaeDbAdapter<T extends object> extends IdaeEventEmitter implements AbstractIdaeDbAdapter<T> {
12
15
  private dbType;
13
16
  private adapter;
@@ -49,5 +52,12 @@ export declare class IdaeDbAdapter<T extends object> extends IdaeEventEmitter im
49
52
  deletedCount?: number;
50
53
  }>;
51
54
  transaction<TResult>(callback: (session: unknown) => Promise<TResult>): Promise<TResult>;
55
+ /**
56
+ * Applies the appropriate adapter for the specified database type.
57
+ * @param collection The name of the collection or table.
58
+ * @param connection The database connection object.
59
+ * @param dbType The type of database being used.
60
+ * @throws {Error} If no adapter is found for the specified database type.
61
+ */
52
62
  private applyAdapter;
53
63
  }
@@ -15,6 +15,9 @@ import { MongoDBAdapter } from './adapters/MongoDBAdapter.js';
15
15
  import { MySQLAdapter } from './adapters/MySQLAdapter.js';
16
16
  import { ChromaDBAdapter } from './adapters/ChromaDBAdapter.js';
17
17
  import { IdaeEventEmitter, withEmitter } from './IdaeEventEmitter.js';
18
+ /**
19
+ * IdaeDbAdapter class that extends IdaeEventEmitter and implements AbstractIdaeDbAdapter.
20
+ */
18
21
  export class IdaeDbAdapter extends IdaeEventEmitter {
19
22
  dbType;
20
23
  adapter;
@@ -99,6 +102,13 @@ export class IdaeDbAdapter extends IdaeEventEmitter {
99
102
  async transaction(callback) {
100
103
  return this.adapter.transaction(callback);
101
104
  }
105
+ /**
106
+ * Applies the appropriate adapter for the specified database type.
107
+ * @param collection The name of the collection or table.
108
+ * @param connection The database connection object.
109
+ * @param dbType The type of database being used.
110
+ * @throws {Error} If no adapter is found for the specified database type.
111
+ */
102
112
  applyAdapter(collection, connection, dbType) {
103
113
  const adapterConstructor = IdaeDbAdapter.adapters.get(dbType);
104
114
  if (!adapterConstructor) {
@@ -1,17 +1,52 @@
1
1
  import { IdaeDBModel } from './IdaeDBModel.js';
2
2
  import { IdaeDb } from './idaeDb.js';
3
+ /**
4
+ * Represents a database connection.
5
+ */
3
6
  export declare class IdaeDbConnection {
4
7
  #private;
5
8
  private _idaeDb;
6
9
  private _dbName;
10
+ /**
11
+ * Creates an instance of IdaeDbConnection.
12
+ * @param _idaeDb The IdaeDb instance.
13
+ * @param _dbName The name of the database.
14
+ */
7
15
  constructor(_idaeDb: IdaeDb, _dbName: string);
16
+ /**
17
+ * Connects to the database.
18
+ * @returns A promise that resolves to the IdaeDbConnection instance.
19
+ */
8
20
  connect(): Promise<IdaeDbConnection>;
21
+ /**
22
+ * Gets the database instance.
23
+ * @returns The database instance.
24
+ * @throws Error if the database is not connected.
25
+ */
9
26
  getDb(): any;
27
+ /**
28
+ * Gets the model for a collection.
29
+ * @param collectionName The name of the collection.
30
+ * @returns The model for the collection.
31
+ */
10
32
  getModel: <T extends Document>(collectionName: string) => IdaeDBModel<T>;
33
+ /**
34
+ * Gets the client instance.
35
+ * @returns The client instance.
36
+ * @throws Error if the client is not initialized.
37
+ */
11
38
  getClient<T>(): T;
39
+ /**
40
+ * Closes the database connection.
41
+ * @returns A promise that resolves when the connection is closed.
42
+ */
12
43
  close(): Promise<void>;
13
44
  get dbName(): string;
14
45
  get connected(): boolean;
15
46
  get idaeDb(): IdaeDb;
47
+ /**
48
+ * Gets the full database name with scope.
49
+ * @returns The full database name.
50
+ */
16
51
  private getFullDbName;
17
52
  }
@@ -2,6 +2,9 @@
2
2
  import { DbType } from './@types/types.js';
3
3
  import { IdaeDBModel } from './IdaeDBModel.js';
4
4
  import { IdaeDb } from './idaeDb.js';
5
+ /**
6
+ * Represents a database connection.
7
+ */
5
8
  export class IdaeDbConnection {
6
9
  _idaeDb;
7
10
  _dbName;
@@ -12,6 +15,11 @@ export class IdaeDbConnection {
12
15
  #client;
13
16
  #adapterClass;
14
17
  #connected = false;
18
+ /**
19
+ * Creates an instance of IdaeDbConnection.
20
+ * @param _idaeDb The IdaeDb instance.
21
+ * @param _dbName The name of the database.
22
+ */
15
23
  constructor(_idaeDb, _dbName) {
16
24
  this._idaeDb = _idaeDb;
17
25
  this._dbName = _dbName;
@@ -21,6 +29,10 @@ export class IdaeDbConnection {
21
29
  // add prefix if requested
22
30
  this._dbName = this.getFullDbName();
23
31
  }
32
+ /**
33
+ * Connects to the database.
34
+ * @returns A promise that resolves to the IdaeDbConnection instance.
35
+ */
24
36
  async connect() {
25
37
  if (!this.#adapterClass?.connect)
26
38
  throw new Error('Adapter does not have a connect method');
@@ -36,12 +48,22 @@ export class IdaeDbConnection {
36
48
  throw error;
37
49
  }
38
50
  }
51
+ /**
52
+ * Gets the database instance.
53
+ * @returns The database instance.
54
+ * @throws Error if the database is not connected.
55
+ */
39
56
  getDb() {
40
57
  if (!this.#Db) {
41
58
  throw new Error('Db not connected. Call connect() first.');
42
59
  }
43
60
  return this.#Db;
44
61
  }
62
+ /**
63
+ * Gets the model for a collection.
64
+ * @param collectionName The name of the collection.
65
+ * @returns The model for the collection.
66
+ */
45
67
  getModel = (collectionName) => {
46
68
  if (!this.#models.has(collectionName)) {
47
69
  const model = new IdaeDBModel(this, collectionName, this._idaeDb?.options?.idaeModelOptions);
@@ -49,12 +71,21 @@ export class IdaeDbConnection {
49
71
  }
50
72
  return this.#models.get(collectionName);
51
73
  };
74
+ /**
75
+ * Gets the client instance.
76
+ * @returns The client instance.
77
+ * @throws Error if the client is not initialized.
78
+ */
52
79
  getClient() {
53
80
  if (!this.#client) {
54
81
  throw new Error('Client not initialized. Call connect() first.');
55
82
  }
56
83
  return this.#client;
57
84
  }
85
+ /**
86
+ * Closes the database connection.
87
+ * @returns A promise that resolves when the connection is closed.
88
+ */
58
89
  async close() {
59
90
  if (!this.#adapterClass?.close)
60
91
  throw new Error('Adapter does not have a close method');
@@ -69,5 +100,9 @@ export class IdaeDbConnection {
69
100
  get idaeDb() {
70
101
  return this._idaeDb;
71
102
  }
103
+ /**
104
+ * Gets the full database name with scope.
105
+ * @returns The full database name.
106
+ */
72
107
  getFullDbName = () => [this.idaeDb.options.dbScope, this._dbName].join('_');
73
108
  }
@@ -24,7 +24,6 @@ export type PreEventListener<T extends unknown[]> = (...args: T) => void | Promi
24
24
  * Type for post-execution event listeners.
25
25
  */
26
26
  export type PostEventListener<T extends unknown[], R> = (result: R, ...args: T) => void | Promise<void>;
27
- export type EventListeners<T, R> = PreEventListener<T> & PostEventListener<T, R> & ErrorEventListener;
28
27
  /**
29
28
  * Type for error event listeners.
30
29
  */
package/dist/idaeDb.d.ts CHANGED
@@ -13,9 +13,17 @@ export type IdaeDbOptions = {
13
13
  idaeModelOptions?: IdaeModelOptions;
14
14
  dbEvents?: EventListeners<object, object>;
15
15
  };
16
+ /**
17
+ * Represents the IdaeDb class.
18
+ */
16
19
  export declare class IdaeDb {
17
20
  #private;
18
21
  private _uri;
22
+ /**
23
+ * Creates an instance of IdaeDb.
24
+ * @param _uri The URI of the database.
25
+ * @param options The options for the database.
26
+ */
19
27
  private constructor();
20
28
  /**
21
29
  * Initializes or retrieves an IdaeDb instance.
@@ -47,11 +55,35 @@ export declare class IdaeDb {
47
55
  * @throws Error if the connection is not found or the database type is unsupported.
48
56
  */
49
57
  collection<T extends Document>(collectionName: string): IdaeDbAdapter<T>;
58
+ /**
59
+ * Closes the current database connection.
60
+ * @returns A Promise that resolves when the connection is closed.
61
+ */
50
62
  closeConnection(): Promise<void>;
63
+ /**
64
+ * Closes all database connections.
65
+ * @returns A Promise that resolves when all connections are closed.
66
+ */
51
67
  closeAllConnections(): Promise<void>;
68
+ /**
69
+ * Gets the adapter class for the current database type.
70
+ * @returns The adapter class.
71
+ */
52
72
  get adapterClass(): import("./@types/types.js").AdapterConstructor<IdaeDbConnection> | undefined;
73
+ /**
74
+ * Gets the connection key for the current database instance.
75
+ * @returns The connection key.
76
+ */
53
77
  get connectionKey(): IdaeDbInstanceKey;
78
+ /**
79
+ * Gets the URI of the database.
80
+ * @returns The URI of the database.
81
+ */
54
82
  get uri(): string;
83
+ /**
84
+ * Gets the options for the database.
85
+ * @returns The options for the database.
86
+ */
55
87
  get options(): IdaeDbOptions;
56
88
  }
57
89
  export {};
package/dist/idaeDb.js CHANGED
@@ -2,6 +2,9 @@
2
2
  import { DbType } from './@types/types.js';
3
3
  import { IdaeDbConnection } from './IdaeDbConnection.js';
4
4
  import { IdaeDbAdapter } from './IdaeDbAdapter.js';
5
+ /**
6
+ * Represents the IdaeDb class.
7
+ */
5
8
  export class IdaeDb {
6
9
  _uri;
7
10
  #globalEvents;
@@ -15,6 +18,11 @@ export class IdaeDb {
15
18
  idaeModelOptions: {},
16
19
  dbEvents: {}
17
20
  };
21
+ /**
22
+ * Creates an instance of IdaeDb.
23
+ * @param _uri The URI of the database.
24
+ * @param options The options for the database.
25
+ */
18
26
  constructor(_uri, options = {}) {
19
27
  this._uri = _uri;
20
28
  this.#options = { ...this.#options, ...options };
@@ -79,6 +87,11 @@ export class IdaeDb {
79
87
  }
80
88
  return adapter;
81
89
  }
90
+ /**
91
+ * Applies event listeners to the adapter.
92
+ * @param adapter The adapter to apply events to.
93
+ * @param events The event listeners to apply.
94
+ */
82
95
  #applyEvents(adapter, events) {
83
96
  for (const [method, listeners] of Object.entries(events)) {
84
97
  if (listeners.pre) {
@@ -92,27 +105,51 @@ export class IdaeDb {
92
105
  }
93
106
  }
94
107
  }
108
+ /**
109
+ * Closes the current database connection.
110
+ * @returns A Promise that resolves when the connection is closed.
111
+ */
95
112
  async closeConnection() {
96
113
  if (this.#connection) {
97
114
  await this.#connection.close();
98
115
  this.#connections.delete(this.connectionKey);
99
116
  }
100
117
  }
118
+ /**
119
+ * Closes all database connections.
120
+ * @returns A Promise that resolves when all connections are closed.
121
+ */
101
122
  async closeAllConnections() {
102
123
  for (const [connectionName, connection] of this.#connections) {
103
124
  await connection.close();
104
125
  }
105
126
  this.#connections.clear();
106
127
  }
128
+ /**
129
+ * Gets the adapter class for the current database type.
130
+ * @returns The adapter class.
131
+ */
107
132
  get adapterClass() {
108
133
  return this.#adapterClass;
109
134
  }
135
+ /**
136
+ * Gets the connection key for the current database instance.
137
+ * @returns The connection key.
138
+ */
110
139
  get connectionKey() {
111
140
  return `${this.options.dbType}:${this._uri}`;
112
141
  }
142
+ /**
143
+ * Gets the URI of the database.
144
+ * @returns The URI of the database.
145
+ */
113
146
  get uri() {
114
147
  return this._uri;
115
148
  }
149
+ /**
150
+ * Gets the options for the database.
151
+ * @returns The options for the database.
152
+ */
116
153
  get options() {
117
154
  return this.#options;
118
155
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@medyll/idae-db",
3
- "version": "0.13.0",
3
+ "version": "0.25.0",
4
4
  "description": "@medyll/idae-db is a flexible and powerful library for interacting with various databases, with a particular focus on MongoDB support. It offers robust connection management, an intuitive API, and simplified CRUD operations.",
5
5
  "scripts": {
6
6
  "dev": "vite dev",
@@ -45,7 +45,7 @@
45
45
  "publint": "^0.2.10",
46
46
  "svelte": "^5.0.0-next.225",
47
47
  "svelte-check": "^3.8.5",
48
- "typescript": "^5.5.4",
48
+ "typescript": "^5.8.2",
49
49
  "typescript-eslint": "^8.1.0",
50
50
  "vite": "^5.4.1",
51
51
  "vitest": "^2.0.5"
@@ -57,4 +57,4 @@
57
57
  "dependencies": {
58
58
  "chromadb": "^1.8.1"
59
59
  }
60
- }
60
+ }