@creator.co/wapi 1.2.4 → 1.2.5

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.
Files changed (49) hide show
  1. package/.github/workflows/npmpublish.yml +1 -1
  2. package/dist/jest.config.js +1 -1
  3. package/dist/jest.config.js.map +1 -1
  4. package/dist/package.json +8 -2
  5. package/dist/src/BaseEvent/Transaction.d.ts +10 -0
  6. package/dist/src/BaseEvent/Transaction.js +147 -37
  7. package/dist/src/BaseEvent/Transaction.js.map +1 -1
  8. package/dist/src/Database/Database.d.ts +18 -0
  9. package/dist/src/Database/Database.js +18 -0
  10. package/dist/src/Database/Database.js.map +1 -0
  11. package/dist/src/Database/DatabaseManager.d.ts +32 -0
  12. package/dist/src/Database/DatabaseManager.js +50 -0
  13. package/dist/src/Database/DatabaseManager.js.map +1 -0
  14. package/dist/src/Database/DatabaseTransaction.d.ts +65 -0
  15. package/dist/src/Database/DatabaseTransaction.js +183 -0
  16. package/dist/src/Database/DatabaseTransaction.js.map +1 -0
  17. package/dist/src/Database/integrations/knex/KnexDatabase.d.ts +22 -0
  18. package/dist/src/Database/integrations/knex/KnexDatabase.js +108 -0
  19. package/dist/src/Database/integrations/knex/KnexDatabase.js.map +1 -0
  20. package/dist/src/Database/integrations/knex/KnexTransaction.d.ts +37 -0
  21. package/dist/src/Database/integrations/knex/KnexTransaction.js +60 -0
  22. package/dist/src/Database/integrations/knex/KnexTransaction.js.map +1 -0
  23. package/dist/src/Database/integrations/pgsql/PostgresDatabase.d.ts +30 -0
  24. package/dist/src/Database/integrations/pgsql/PostgresDatabase.js +108 -0
  25. package/dist/src/Database/integrations/pgsql/PostgresDatabase.js.map +1 -0
  26. package/dist/src/Database/integrations/pgsql/PostgresTransaction.d.ts +37 -0
  27. package/dist/src/Database/integrations/pgsql/PostgresTransaction.js +60 -0
  28. package/dist/src/Database/integrations/pgsql/PostgresTransaction.js.map +1 -0
  29. package/dist/src/Server/lib/container/Proxy.js +3 -2
  30. package/dist/src/Server/lib/container/Proxy.js.map +1 -1
  31. package/jest.config.ts +1 -1
  32. package/package.json +8 -2
  33. package/src/BaseEvent/Transaction.ts +48 -18
  34. package/src/Database/Database.ts +19 -0
  35. package/src/Database/DatabaseManager.ts +51 -0
  36. package/src/Database/DatabaseTransaction.ts +118 -0
  37. package/src/Database/integrations/knex/KnexDatabase.ts +47 -0
  38. package/src/Database/integrations/knex/KnexTransaction.ts +51 -0
  39. package/src/Database/integrations/pgsql/PostgresDatabase.ts +49 -0
  40. package/src/Database/integrations/pgsql/PostgresTransaction.ts +54 -0
  41. package/src/Database/types.d.ts +49 -0
  42. package/src/Server/lib/container/Proxy.ts +2 -1
  43. package/tests/BaseEvent/Transaction.test.ts +59 -0
  44. package/tests/Database/DatabaseManager.test.ts +55 -0
  45. package/tests/Database/integrations/knex/KnexDatabase.test.ts +53 -0
  46. package/tests/Database/integrations/knex/KnexTransaction.test.ts +133 -0
  47. package/tests/Database/integrations/pg/PostgresDatabase.test.ts +50 -0
  48. package/tests/Database/integrations/pg/PostgresTransaction.test.ts +51 -0
  49. package/tsconfig.json +5 -0
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.PostgresTransactionImpl = void 0;
19
+ var DatabaseTransaction_1 = require("../../DatabaseTransaction");
20
+ /**
21
+ * Represents a transaction in a Postgres database.
22
+ */
23
+ var PostgresTransactionImpl = /** @class */ (function (_super) {
24
+ __extends(PostgresTransactionImpl, _super);
25
+ /**
26
+ * Constructs a new instance of the private class.
27
+ * @param {PoolClient} delegate - The delegate object.
28
+ * @param {PostgresDatabase} database - The database object.
29
+ * @returns None
30
+ */
31
+ function PostgresTransactionImpl(delegate, database) {
32
+ return _super.call(this, delegate, database) || this;
33
+ }
34
+ /**
35
+ * Static factory method for creating a new instance, wrapping a delegate PoolClient.
36
+ * @param {PoolClient} delegate - The delegate client to wrap.
37
+ * @param {PostgresDatabase} database - The PostgresDatabase instance associated with the transaction.
38
+ * @returns {PostgresTransaction} - A wrapped PostgresTransaction instance.
39
+ */
40
+ PostgresTransactionImpl.wrapDelegate = function (delegate, database) {
41
+ return DatabaseTransaction_1.DatabaseTransaction.wrapInstance(new PostgresTransactionImpl(delegate, database));
42
+ };
43
+ /**
44
+ * Commits the current transaction.
45
+ * @returns A promise that resolves when the commit is successful.
46
+ */
47
+ PostgresTransactionImpl.prototype.doCommit = function () {
48
+ return this.delegate.query('COMMIT');
49
+ };
50
+ /**
51
+ * Performs a rollback operation in the database.
52
+ * @returns A promise that resolves when the rollback operation is completed.
53
+ */
54
+ PostgresTransactionImpl.prototype.doRollback = function () {
55
+ return this.delegate.query('ROLLBACK');
56
+ };
57
+ return PostgresTransactionImpl;
58
+ }(DatabaseTransaction_1.DatabaseTransaction));
59
+ exports.PostgresTransactionImpl = PostgresTransactionImpl;
60
+ //# sourceMappingURL=PostgresTransaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PostgresTransaction.js","sourceRoot":"","sources":["../../../../../src/Database/integrations/pgsql/PostgresTransaction.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAGA,iEAA+D;AAQ/D;;GAEG;AACH;IAA6C,2CAAmB;IAC9D;;;;;OAKG;IACH,iCAAoB,QAAoB,EAAE,QAA0B;eAClE,kBAAM,QAAQ,EAAE,QAAQ,CAAC;IAC3B,CAAC;IAED;;;;;OAKG;IACW,oCAAY,GAA1B,UACE,QAAoB,EACpB,QAA0B;QAE1B,OAAO,yCAAmB,CAAC,YAAY,CAAC,IAAI,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAQ,CAAA;IACjG,CAAC;IAED;;;OAGG;IACO,0CAAQ,GAAlB;QACE,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IACtC,CAAC;IAED;;;OAGG;IACO,4CAAU,GAApB;QACE,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;IACxC,CAAC;IACH,8BAAC;AAAD,CAAC,AAvCD,CAA6C,yCAAmB,GAuC/D;AAvCY,0DAAuB"}
@@ -167,8 +167,9 @@ var Proxy = /** @class */ (function () {
167
167
  console.debug('[Proxy] - [STOPPING]');
168
168
  return [2 /*return*/, new Promise(function (resolve) {
169
169
  _this.listener.close(function (_err) {
170
- if (err || _err)
171
- console.log('[Proxy] - exit output:', err || _err);
170
+ var err2 = err || _err;
171
+ if (err2)
172
+ console.log('[Proxy] - exit output:', err2);
172
173
  console.log('[Proxy] - [STOPPED]');
173
174
  process.exit(err || _err ? 1 : 0);
174
175
  resolve(null);
@@ -1 +1 @@
1
- {"version":3,"file":"Proxy.js","sourceRoot":"","sources":["../../../../../src/Server/lib/container/Proxy.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6BAAyD;AAEzD,2BAA4B;AAC5B,iCAAkC;AAGlC,mDAA6C;AAC7C,iDAA2C;AAC3C,yDAAgE;AAChE,4CAAsC;AACtC,4CAAsC;AAGtC;;;;;;GAMG;AACH;IAuCE;;;;;;OAMG;IACH,eAAY,MAAoB,EAAE,iBAAkD;QAClF,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAA;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,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,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAA;IAC9F,CAAC;IACH,YAAC;AAAD,CAAC,AAlKD,IAkKC"}
package/jest.config.ts CHANGED
@@ -19,7 +19,7 @@ const config: Config.InitialOptions = {
19
19
  ],
20
20
  ],
21
21
  coverageReporters: ['clover', 'json', 'lcov', ['text', { file: 'coverage.txt' }], 'json-summary'],
22
- collectCoverageFrom: ['src/**/*.(t|j)s'],
22
+ collectCoverageFrom: ['src/**/*.(t|j)s', '!src/**/*.d.(t|j)s'],
23
23
  coverageThreshold: {
24
24
  global: {
25
25
  branches: 80,
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@creator.co/wapi",
3
- "version": "1.2.4",
3
+ "version": "1.2.5",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "type": "commonjs",
8
8
  "scripts": {
9
- "build": "npm run lint && tsc --build",
9
+ "build": "tsc --build",
10
10
  "clean": "tsc --build --clean",
11
11
  "lint-fix": "eslint . --ext .ts --fix",
12
12
  "lint": "eslint . --ext .ts",
@@ -24,6 +24,7 @@
24
24
  "@aws-sdk/credential-provider-node": "^3.414.0",
25
25
  "@types/email-templates": "^10.0.1",
26
26
  "@types/nodemailer": "^6.4.10",
27
+ "@types/object-hash": "^3.0.4",
27
28
  "abind": "^1.0.5",
28
29
  "cors": "^2.8.5",
29
30
  "cuid": "^3.0.0",
@@ -32,18 +33,23 @@
32
33
  "express": "^4.18.2",
33
34
  "json-stringify-safe": "^5.0.1",
34
35
  "jsonwebtoken": "^9.0.2",
36
+ "knex": "^3.0.1",
35
37
  "node-cache": "^5.1.2",
38
+ "object-hash": "^3.0.0",
36
39
  "parse-duration": "^1.1.0",
40
+ "pg": "^8.11.3",
37
41
  "sha1": "^1.1.1",
38
42
  "stack-trace": "0.0.10",
39
43
  "zod": "^3.22.4"
40
44
  },
41
45
  "devDependencies": {
42
46
  "@types/aws-lambda": "^8.10.119",
47
+ "@types/chai": "^4.3.9",
43
48
  "@types/express": "^4.17.19",
44
49
  "@types/jest": "^29.5.6",
45
50
  "@types/jsonwebtoken": "^9.0.3",
46
51
  "@types/node": "^20.5.7",
52
+ "@types/pg": "^8.10.5",
47
53
  "@typescript-eslint/eslint-plugin": "^6.5.0",
48
54
  "@typescript-eslint/parser": "^6.5.0",
49
55
  "aws-lambda": "^1.0.7",
@@ -2,6 +2,9 @@ import type { APIGatewayEvent, Context, SQSEvent } from 'aws-lambda'
2
2
 
3
3
  import Request from '../API/Request'
4
4
  import Response, { ResponseErrorType } from '../API/Response'
5
+ import { DatabaseManager } from '../Database/DatabaseManager'
6
+ import { DatabaseTransaction } from '../Database/DatabaseTransaction'
7
+ import type { DatabaseTransactionType, DatabaseType, DbConfig } from '../Database/types'
5
8
  import Globals from '../Globals'
6
9
  import Logger, { LoggerConfig } from '../Logger/Logger'
7
10
  import Publisher, { PublisherConfig } from '../Publisher/Publisher'
@@ -24,6 +27,8 @@ export default class Transaction<
24
27
  ResponseInnerType = null,
25
28
  MiscRespType = null,
26
29
  > {
30
+ private databaseManager: DatabaseManager = DatabaseManager.INSTANCE
31
+ private transactions: DatabaseTransaction[] = []
27
32
  private event: any
28
33
  private context: Context
29
34
  private response: Response<ResponseInnerType | ResponseErrorType> | MiscRespType | null
@@ -34,6 +39,7 @@ export default class Transaction<
34
39
  public readonly request: Request<InputType>
35
40
  public readonly publisher: Publisher
36
41
  public responseProxy: (response: Response<ResponseInnerType>) => Promise<void>
42
+
37
43
  //
38
44
  constructor(event: APIGatewayEvent | SQSEvent, context: Context, config?: TransactionConfig) {
39
45
  const transactionId = context.awsRequestId
@@ -74,6 +80,7 @@ export default class Transaction<
74
80
  // allow request to async succeed through lambda context
75
81
  return null
76
82
  }
83
+
77
84
  //Executions
78
85
  private async iexecute(
79
86
  executionFunc: TransactionExecution<
@@ -119,32 +126,54 @@ export default class Transaction<
119
126
  }
120
127
  return executionFailed
121
128
  }
122
- private async executeDBTransactions(safeExecution) {
129
+
130
+ /**
131
+ * Retrieves a database transaction for the specified database configuration.
132
+ * @async
133
+ * @param {DbConfig<S>} config - The configuration object for the database.
134
+ * @returns {Promise<DatabaseTransactionType<S>>} A promise that resolves to the database transaction.
135
+ */
136
+ public async getDbTransaction<S extends DatabaseType>(
137
+ config: DbConfig<S>
138
+ ): Promise<DatabaseTransactionType<S>> {
139
+ const db = this.databaseManager.create(config)
140
+ const dbTrans = await db.transaction()
141
+ this.transactions.push(dbTrans)
142
+ return dbTrans as any
143
+ }
144
+
145
+ private async executeDBTransactions(safeExecution: () => Promise<boolean>): Promise<void> {
123
146
  try {
124
- // //start DB
125
- // if (this.db) await this.db.connect();
126
- // //start transaction
127
- // if (this.db) await this.db.beginTransaction();
128
- // //
129
- // let executionFailed =
130
- await safeExecution()
131
- // //Commit if not failed, rollback if failed
132
- // if (!executionFailed) {
133
- // if (this.db) await this.db.commit();
134
- // } else {
135
- // this.logger.log("Rolling back DB transactions. Main code failed!");
136
- // if (this.db) await this.db.rollback();
137
- // }
138
- // //Cleanup DB after execution
139
- // if (this.db) await this.db.cleanup();
147
+ // Execute
148
+ const execFailed = await safeExecution()
149
+ for (const transaction of [...this.transactions].reverse()) {
150
+ try {
151
+ await transaction[execFailed ? 'closeFailure' : 'closeSuccess']()
152
+ } catch (e) {
153
+ // TODO: should we keep committing transactions even if one fails?
154
+ this.logger.error('Exception when closing DB transactions after success.')
155
+ this.logger.exception(e)
156
+ }
157
+ }
140
158
  } catch (e) {
159
+ /* this part of the code handle exceptions at transaction level,
160
+ so probably a bug but we still handle such */
161
+ for (const transaction of [...this.transactions].reverse()) {
162
+ try {
163
+ await transaction.closeFailure()
164
+ } catch (e) {
165
+ this.logger.error('Exception when closing DB transactions after failure.')
166
+ this.logger.exception(e)
167
+ }
168
+ }
141
169
  this.logger.error('Exception when executing DB transactions.')
142
170
  this.logger.log(e.stack)
143
171
  //retrow?
144
172
  if (this.retrowErrors) throw e
145
173
  }
146
174
  }
147
- private async executeLoggerFlush(safeExecution) {
175
+
176
+ private async executeLoggerFlush(safeExecution): Promise<void> {
148
177
  try {
149
178
  await safeExecution()
150
179
  } catch (e) {
@@ -156,6 +185,7 @@ export default class Transaction<
156
185
  this.logger.debug('Transaction ended')
157
186
  }
158
187
  }
188
+
159
189
  /* Response support */
160
190
  private getErrorResponse(error: string, code: string): Response<ResponseErrorType> {
161
191
  return Response.BadRequestResponseWithRollback(error, code)
@@ -0,0 +1,19 @@
1
+ import { DatabaseTransaction } from './DatabaseTransaction'
2
+ import type { DbConfig } from './types'
3
+
4
+ /**
5
+ * Abstract class representing a database.
6
+ * @template T - The type of database transaction.
7
+ */
8
+ export abstract class Database<T extends DatabaseTransaction> {
9
+ /**
10
+ * Creates a database instance, maintaining a reference to the database configuration.
11
+ */
12
+ protected constructor(public readonly config: DbConfig<any>) {}
13
+
14
+ /**
15
+ * Returns a promise resolving to a new instance of the transaction impl.
16
+ * @returns A promise that resolves to a transaction instance.
17
+ */
18
+ public abstract transaction(): Promise<T>
19
+ }
@@ -0,0 +1,51 @@
1
+ import * as hash from 'object-hash'
2
+
3
+ import { KnexDatabase } from './integrations/knex/KnexDatabase'
4
+ import { PostgresDatabase } from './integrations/pgsql/PostgresDatabase'
5
+ import type { DatabaseImplType, DatabaseType, DbConfig } from './types'
6
+
7
+ /**
8
+ * An object that maps database names to their corresponding database classes.
9
+ * @type {Object}
10
+ * @property {KnexDatabase} knex - The Knex database class.
11
+ * @property {PostgresDatabase} pg - The Postgres database class.
12
+ */
13
+ export const DATABASES = {
14
+ knex: KnexDatabase,
15
+ pg: PostgresDatabase,
16
+ }
17
+
18
+ /**
19
+ * A class that manages databases and provides methods for creating and accessing database instances.
20
+ */
21
+ export class DatabaseManager {
22
+ /**
23
+ * The singleton instance of the DatabaseManager class.
24
+ */
25
+ public static readonly INSTANCE = new DatabaseManager()
26
+ private databases: typeof DATABASES = DATABASES
27
+
28
+ private instances: { [k: string]: DatabaseImplType<any> } = {}
29
+
30
+ /**
31
+ * Creates a new instance of a database based on the provided configuration.
32
+ * @param {DbConfig<S>} config - The configuration object for the database.
33
+ * @returns {DatabaseImplType<S>} - The created database instance.
34
+ * @template S - The type of the database.
35
+ */
36
+ public create<S extends DatabaseType>(config: DbConfig<S>): DatabaseImplType<S> {
37
+ const configHash = hash(config)
38
+ if (this.instances[configHash]) {
39
+ return this.instances[configHash] as any
40
+ }
41
+ const instance = this.instantiateDb(config as any)
42
+ this.instances[configHash] = instance
43
+ return instance as any
44
+ }
45
+
46
+ private instantiateDb(
47
+ config: DbConfig<'knex'> | DbConfig<'pg'>
48
+ ): KnexDatabase | PostgresDatabase {
49
+ return new this.databases[config.type](config as any)
50
+ }
51
+ }
@@ -0,0 +1,118 @@
1
+ import { Database } from './Database'
2
+
3
+ /**
4
+ * Abstract class representing a database transaction.
5
+ * @class DatabaseTransaction
6
+ */
7
+ export abstract class DatabaseTransaction {
8
+ private _isOpen: boolean = true
9
+ protected delegate: any
10
+ protected database: Database<any>
11
+
12
+ /**
13
+ * Returns a boolean value indicating whether the transaction is open or not.
14
+ * @returns {boolean} - true if the object is open, false otherwise.
15
+ */
16
+ public get isOpen(): boolean {
17
+ return this._isOpen
18
+ }
19
+
20
+ /**
21
+ * Constructs a new instance of the class.
22
+ * @param {any} delegate - The delegate object.
23
+ * @param {Database<any>} database - The database object.
24
+ * @protected
25
+ */
26
+ protected constructor(delegate: any, database: Database<any>) {
27
+ this.delegate = delegate
28
+ this.database = database
29
+ }
30
+
31
+ /**
32
+ * Wraps an instance of a subclass of DatabaseTransaction with a Proxy object.
33
+ * The Proxy object intercepts method calls and delegates to the target instance.
34
+ * If the method is on the target instance, it is called directly.
35
+ * If the method is not on the target instance and the transaction is open, it is called on the target's delegate implementation.
36
+ * If the method is not on the target instance and the transaction is closed, an error is thrown.
37
+ * @param {T} subclass - The subclass instance to wrap with a Proxy.
38
+ * @returns {T} - The wrapped subclass instance.
39
+ * @throws {Error} - If the target instance is closed.
40
+ */
41
+ protected static wrapInstance<T extends DatabaseTransaction>(subclass: T): T {
42
+ const bind = (target: any, key: string | symbol) =>
43
+ typeof target[key] === 'function' ? target[key].bind(target) : target[key]
44
+
45
+ return new Proxy<T>(subclass, {
46
+ get(target: T, p: string | symbol): any {
47
+ if (target[p] !== undefined) {
48
+ return bind(target, p)
49
+ } else if (target._isOpen) {
50
+ return bind(target.delegate, p)
51
+ }
52
+ return undefined
53
+ },
54
+ })
55
+ }
56
+
57
+ /**
58
+ * Commits the transaction.
59
+ * @throws {Error} - If the transaction is already closed.
60
+ * @returns None
61
+ */
62
+ public async commit(): Promise<void> {
63
+ if (!this._isOpen) {
64
+ throw new Error('Cannot commit, transaction is already closed!')
65
+ }
66
+ await this.doCommit()
67
+ this._isOpen = false
68
+ }
69
+
70
+ /**
71
+ * Rollbacks the current transaction.
72
+ * @throws {Error} - If the transaction is already closed.
73
+ * @returns {Promise<void>} - A promise that resolves once the rollback is complete.
74
+ */
75
+ public async rollback(): Promise<void> {
76
+ if (!this._isOpen) {
77
+ throw new Error('Cannot rollback, transaction is already closed!')
78
+ }
79
+ await this.doRollback()
80
+ this._isOpen = false
81
+ }
82
+
83
+ /**
84
+ * Closes the transaction after a successful execution.
85
+ * @returns {Promise<void>} - A promise that resolves once the necessary actions are completed.
86
+ */
87
+ public async closeSuccess() {
88
+ if (this._isOpen) {
89
+ if (this.database.config.autoCommit) {
90
+ await this.doCommit()
91
+ } else {
92
+ await this.doRollback()
93
+ }
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Closes the transaction after a failed execution.
99
+ * @returns {Promise<void>} - A promise that resolves once the necessary actions are completed.
100
+ */
101
+ public async closeFailure() {
102
+ if (this._isOpen) {
103
+ await this.doRollback()
104
+ }
105
+ }
106
+
107
+ /**
108
+ * An abstract method that performs the commit operation.
109
+ * @returns {Promise<any>} A promise that resolves when the commit operation is completed.
110
+ */
111
+ protected abstract doCommit(): Promise<any>
112
+
113
+ /**
114
+ * An abstract method that performs a rollback operation.
115
+ * @returns A Promise that resolves when the rollback operation is complete.
116
+ */
117
+ protected abstract doRollback(): Promise<any>
118
+ }
@@ -0,0 +1,47 @@
1
+ import knex, { Knex } from 'knex'
2
+
3
+ import { KnexTransaction, KnexTransactionImpl } from './KnexTransaction'
4
+ import { Database } from '../../Database'
5
+ import type { DbConfig } from '../../types'
6
+
7
+ /**
8
+ * Represents a Knex database connection.
9
+ * @extends Database<KnexTransaction>
10
+ */
11
+ export class KnexDatabase extends Database<KnexTransaction> {
12
+ private static knexProvider: (config: knex.Knex.Config<any>) => knex.Knex<any, unknown[]> = knex
13
+
14
+ private client: Knex
15
+
16
+ /**
17
+ * Constructs a new instance of the database class using the provided configuration.
18
+ * @param {DbConfig<'knex'>} config - The configuration object for the database.
19
+ * @returns None
20
+ */
21
+ public constructor(config: DbConfig<'knex'>) {
22
+ super(config)
23
+ this.client = KnexDatabase.knexProvider({
24
+ client: config.driver,
25
+ connection: {
26
+ host: config.host,
27
+ port: config.port,
28
+ user: config.username,
29
+ password: config.password,
30
+ database: config.database,
31
+ },
32
+ pool: {
33
+ min: 1,
34
+ max: config.maxConnections,
35
+ },
36
+ })
37
+ }
38
+
39
+ /**
40
+ * Initiates a transaction using the underlying database client.
41
+ * @returns {Promise<KnexTransaction>} A promise that resolves to a KnexTransaction object representing the transaction.
42
+ */
43
+ public override async transaction(): Promise<KnexTransaction> {
44
+ const delegate = await this.client.transaction()
45
+ return KnexTransactionImpl.wrapDelegate(delegate, this)
46
+ }
47
+ }
@@ -0,0 +1,51 @@
1
+ import { Knex } from 'knex'
2
+
3
+ import { KnexDatabase } from './KnexDatabase'
4
+ import { DatabaseTransaction } from '../../DatabaseTransaction'
5
+
6
+ /**
7
+ * A type alias for a Knex transaction object.
8
+ * @typedef {KnexTransactionImpl & Knex.Transaction} KnexTransaction
9
+ */
10
+ export type KnexTransaction = KnexTransactionImpl & Knex.Transaction
11
+
12
+ /**
13
+ * Implementation of a Knex transaction that extends the DatabaseTransaction class.
14
+ */
15
+ export class KnexTransactionImpl extends DatabaseTransaction {
16
+ /**
17
+ * Constructs a new instance of the private class.
18
+ * @param {Knex.Transaction} delegate - The delegate transaction object.
19
+ * @param {KnexDatabase} database - The database object.
20
+ * @returns None
21
+ */
22
+ private constructor(delegate: Knex.Transaction, database: KnexDatabase) {
23
+ super(delegate, database)
24
+ }
25
+
26
+ /**
27
+ * Wraps a delegate transaction object with a custom implementation of the KnexTransaction interface.
28
+ * @param {Knex.Transaction} delegate - The delegate transaction object to wrap.
29
+ * @param {KnexDatabase} database - The KnexDatabase instance associated with the transaction.
30
+ * @returns {KnexTransaction} - The wrapped transaction object.
31
+ */
32
+ public static wrapDelegate(delegate: Knex.Transaction, database: KnexDatabase): KnexTransaction {
33
+ return DatabaseTransaction.wrapInstance(new KnexTransactionImpl(delegate, database)) as any
34
+ }
35
+
36
+ /**
37
+ * Commits the changes made by the delegate object.
38
+ * @returns None
39
+ */
40
+ protected doCommit() {
41
+ return this.delegate.commit()
42
+ }
43
+
44
+ /**
45
+ * Performs a rollback operation by calling the rollback method of the delegate object.
46
+ * @returns None
47
+ */
48
+ protected doRollback() {
49
+ return this.delegate.rollback()
50
+ }
51
+ }
@@ -0,0 +1,49 @@
1
+ import { Pool } from 'pg'
2
+
3
+ import { PostgresTransaction, PostgresTransactionImpl } from './PostgresTransaction'
4
+ import { Database } from '../../Database'
5
+ import type { DbConfig } from '../../types'
6
+
7
+ /**
8
+ * Represents a Postgres database connection.
9
+ * @extends Database<PostgresTransaction>
10
+ */
11
+ export class PostgresDatabase extends Database<PostgresTransaction> {
12
+ /**
13
+ * A private static property that represents a connection pool for a PostgreSQL database.
14
+ */
15
+ private static pgProvider = Pool
16
+ /**
17
+ * The client property represents a connection pool to a database.
18
+ * @private
19
+ * @type {Pool}
20
+ */
21
+ private client: Pool
22
+
23
+ /**
24
+ * Constructs a new instance of the class with the given database configuration.
25
+ * @param {DbConfig<'pg'>} config - The configuration object for the PostgreSQL database.
26
+ * @returns None
27
+ */
28
+ public constructor(config: DbConfig<'pg'>) {
29
+ super(config)
30
+ this.client = new PostgresDatabase.pgProvider({
31
+ host: config.host,
32
+ port: config.port,
33
+ user: config.username,
34
+ password: config.password,
35
+ database: config.database,
36
+ max: config.maxConnections,
37
+ })
38
+ }
39
+
40
+ /**
41
+ * Initiates a new transaction in the PostgreSQL database.
42
+ * @returns {Promise<PostgresTransaction>} A promise that resolves to a PostgresTransaction object representing the new transaction.
43
+ */
44
+ public override async transaction(): Promise<PostgresTransaction> {
45
+ const delegate = await this.client.connect()
46
+ await delegate.query('BEGIN')
47
+ return PostgresTransactionImpl.wrapDelegate(delegate, this)
48
+ }
49
+ }
@@ -0,0 +1,54 @@
1
+ import { PoolClient } from 'pg'
2
+
3
+ import { PostgresDatabase } from './PostgresDatabase'
4
+ import { DatabaseTransaction } from '../../DatabaseTransaction'
5
+
6
+ /**
7
+ * A type alias representing a Postgres transaction. It extends the `PostgresTransactionImpl`
8
+ * interface and includes the `PoolClient` interface.
9
+ */
10
+ export type PostgresTransaction = PostgresTransactionImpl & PoolClient
11
+
12
+ /**
13
+ * Represents a transaction in a Postgres database.
14
+ */
15
+ export class PostgresTransactionImpl extends DatabaseTransaction {
16
+ /**
17
+ * Constructs a new instance of the private class.
18
+ * @param {PoolClient} delegate - The delegate object.
19
+ * @param {PostgresDatabase} database - The database object.
20
+ * @returns None
21
+ */
22
+ private constructor(delegate: PoolClient, database: PostgresDatabase) {
23
+ super(delegate, database)
24
+ }
25
+
26
+ /**
27
+ * Static factory method for creating a new instance, wrapping a delegate PoolClient.
28
+ * @param {PoolClient} delegate - The delegate client to wrap.
29
+ * @param {PostgresDatabase} database - The PostgresDatabase instance associated with the transaction.
30
+ * @returns {PostgresTransaction} - A wrapped PostgresTransaction instance.
31
+ */
32
+ public static wrapDelegate(
33
+ delegate: PoolClient,
34
+ database: PostgresDatabase
35
+ ): PostgresTransaction {
36
+ return DatabaseTransaction.wrapInstance(new PostgresTransactionImpl(delegate, database)) as any
37
+ }
38
+
39
+ /**
40
+ * Commits the current transaction.
41
+ * @returns A promise that resolves when the commit is successful.
42
+ */
43
+ protected doCommit() {
44
+ return this.delegate.query('COMMIT')
45
+ }
46
+
47
+ /**
48
+ * Performs a rollback operation in the database.
49
+ * @returns A promise that resolves when the rollback operation is completed.
50
+ */
51
+ protected doRollback() {
52
+ return this.delegate.query('ROLLBACK')
53
+ }
54
+ }