@@ -11,12 +11,41 @@ interface PrismaClient {
11
11
$disconnect ( ) : Promise < void > ;
12
12
}
13
13
14
+ /**
15
+ * Create a postgres client and connect it to the database
16
+ *
17
+ * @param config the kapeta config provider
18
+ * @param resourceName the resource name within the block
19
+ * @param createClient a function that creates the prisma client
20
+ */
21
+ export const createPostgresDBClient = async < T extends PrismaClient > ( config :ConfigProvider , resourceName : string , createClient : ( opts : any ) => T ) => {
22
+ const url = await createDBURI ( config , resourceName ) ;
23
+ console . log ( 'Connecting to postgres database: %s' , resourceName ) ;
24
+
25
+ const prisma = createClient ( {
26
+ datasources : {
27
+ db : {
28
+ url
29
+ } ,
30
+ } ,
31
+ } ) ;
32
+
33
+ await prisma . $connect ( ) ;
34
+ console . log ( 'Connected successfully to postgres database: %s' , resourceName ) ;
35
+ return prisma ;
36
+ }
14
37
38
+ /**
39
+ * A base class for postgres databases.
40
+ *
41
+ * See also {@link createPostgresDBClient} which is the recommended way to create a postgres client.
42
+ */
15
43
export abstract class PostgresDB < T extends PrismaClient > {
16
44
private readonly _resourceName : string ;
17
45
private _ready : boolean = false ;
18
46
private _prisma ?: T ;
19
- constructor ( resourceName :string ) {
47
+
48
+ protected constructor ( resourceName :string ) {
20
49
this . _resourceName = resourceName ;
21
50
Config . onReady ( async ( provider ) => {
22
51
await this . init ( provider ) ;
@@ -26,19 +55,7 @@ export abstract class PostgresDB<T extends PrismaClient> {
26
55
abstract createClient ( opts : any ) : T ;
27
56
28
57
async init ( provider : ConfigProvider ) {
29
- const url = await createDBURI ( provider , this . _resourceName ) ;
30
- console . log ( 'Connecting to postgres database: %s' , url ) ;
31
-
32
- this . _prisma = this . createClient ( {
33
- datasources : {
34
- db : {
35
- url
36
- } ,
37
- } ,
38
- } ) ;
39
-
40
- await this . _prisma . $connect ( ) ;
41
- console . log ( 'Connected successfully to postgres database: %s' , url ) ;
58
+ this . _prisma = await createPostgresDBClient ( provider , this . _resourceName , this . createClient ) ;
42
59
this . _ready = true ;
43
60
}
44
61
0 commit comments