declapract-typescript-ehmpathy 0.30.3 → 0.31.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/dist/practices/persist-with-rds/best-practice/src/utils/database/withDatabaseContext.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DatabaseConnection,
|
|
3
|
+
getDatabaseConnection,
|
|
4
|
+
} from './getDatabaseConnection';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* wraps the function to provide a managed database connection to it's context, if one was not already passed in
|
|
8
|
+
*
|
|
9
|
+
* note
|
|
10
|
+
* - manages the database connection it gives to the function by opening it and closing it once the function finishes
|
|
11
|
+
* - if a database connection was passed in as part of the arguments, it will instead use that one and will not close it once it finishes (useful for transactions)
|
|
12
|
+
*
|
|
13
|
+
* example usage:
|
|
14
|
+
* ```
|
|
15
|
+
* const findById = withDatabaseConnection(({ id }: { id: string }, context: { dbConnection: DatabaseConnection }) => {
|
|
16
|
+
* // do logic with dbConnection
|
|
17
|
+
* });
|
|
18
|
+
* // ...
|
|
19
|
+
* await findById({ id: 821 }); // note how we don't have to pass in the dbConnection
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export const withDatabaseContext = <
|
|
23
|
+
P1,
|
|
24
|
+
P2 extends { dbConnection: DatabaseConnection },
|
|
25
|
+
R,
|
|
26
|
+
>(
|
|
27
|
+
logic: (input: P1, context: P2) => R | Promise<R>,
|
|
28
|
+
) => {
|
|
29
|
+
return async (
|
|
30
|
+
input: P1,
|
|
31
|
+
context: Omit<P2, 'dbConnection'> & { dbConnection?: DatabaseConnection },
|
|
32
|
+
) => {
|
|
33
|
+
// open the db connection, if one was not given
|
|
34
|
+
const dbConnection =
|
|
35
|
+
context.dbConnection ?? (await getDatabaseConnection());
|
|
36
|
+
|
|
37
|
+
// try and run the logic with db connection
|
|
38
|
+
try {
|
|
39
|
+
return await logic(input, { ...context, dbConnection } as P2); // as P2 because: https://github.com/microsoft/TypeScript/issues/35858
|
|
40
|
+
} finally {
|
|
41
|
+
// make sure to close the db connection, both when `logic` throws an error or succeeds
|
|
42
|
+
if (!context.dbConnection) await dbConnection.end();
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "declapract-typescript-ehmpathy",
|
|
3
3
|
"author": "ehmpathy",
|
|
4
4
|
"description": "declapract best practices declarations for typescript",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.31.0",
|
|
6
6
|
"main": "src/index.js",
|
|
7
7
|
"repository": "ehmpathy/declapract-typescript-ehmpathy",
|
|
8
8
|
"homepage": "https://github.com/ehmpathy/declapract-typescript-ehmpathy",
|