1
+ import { ConfigService } from "@nestjs/config" ;
2
+ import { TypeOrmModuleOptions } from "@nestjs/typeorm" ;
3
+ import { join } from 'path' ;
4
+ import { readdirSync , statSync } from 'fs' ;
5
+
6
+ export class PostgresDatabase {
7
+ constructor ( private readonly configService : ConfigService ) { }
8
+
9
+ getConnection ( ) : TypeOrmModuleOptions {
10
+ const entities = PostgresDatabase . loadEntities ( )
11
+ return {
12
+ type : 'postgres' ,
13
+ host : this . configService . get < string > ( 'DB_HOST' , 'localhost' ) ,
14
+ port : this . configService . get < number > ( 'DB_PORT' , 5432 ) ,
15
+ username : this . configService . get < string > ( 'DB_USERNAME' , 'user' ) ,
16
+ password : this . configService . get < string > ( 'DB_PASSWORD' , 'password' ) ,
17
+ database : this . configService . get < string > ( 'DB_NAME' , 'my_database' ) ,
18
+ entities,
19
+ synchronize : false , // Set to false in production
20
+ logging : false , // Disable logging in production
21
+ }
22
+ }
23
+
24
+ private static loadEntitiesFromDirectory ( directoryPath : string ) : any [ ] {
25
+ let entities : any [ ] = [ ]
26
+
27
+ try {
28
+ const files = readdirSync ( directoryPath )
29
+ files . forEach ( ( file ) => {
30
+ const fullPath = join ( directoryPath , file )
31
+ const fileStat = statSync ( fullPath )
32
+
33
+ // If it's a directory, recursively look for entities
34
+ if ( fileStat . isDirectory ( ) ) {
35
+ entities = [ ...entities , ...this . loadEntitiesFromDirectory ( fullPath ) ]
36
+ } else if ( file . endsWith ( '.orm-entity.ts' ) || file . endsWith ( '.orm-entity.js' ) ) {
37
+ // If it matches the entity file format, load it
38
+ entities . push ( require ( fullPath ) . default )
39
+ }
40
+ } )
41
+ } catch ( error ) {
42
+ console . error ( `Error reading directory ${ directoryPath } : ` , error )
43
+ }
44
+
45
+ return entities
46
+ }
47
+
48
+ private static loadEntities ( ) : any [ ] {
49
+ const rootPath = join ( __dirname , '../../' )
50
+
51
+ console . log ( 'Root path: ' , rootPath )
52
+ const entities : any [ ] = [ ]
53
+
54
+ // Traverse the entire directory, looking for all entities folders
55
+ const traverseDir = ( dir : string ) => {
56
+ const files = readdirSync ( dir )
57
+
58
+ files . forEach ( ( file ) => {
59
+ const fullPath = join ( dir , file )
60
+ const fileStat = statSync ( fullPath )
61
+
62
+ if ( fileStat . isDirectory ( ) ) {
63
+
64
+ if ( file . toLowerCase ( ) === 'entities' ) {
65
+ // If it's an entities folder, load the entities inside
66
+ const entityFiles = this . loadEntitiesFromDirectory ( fullPath )
67
+
68
+ entities . push ( ...entityFiles )
69
+ } else {
70
+ traverseDir ( fullPath ) // If it's not an entities folder, continue recursion
71
+ }
72
+ }
73
+ } )
74
+ }
75
+
76
+ // Start traversing the src or dist folder
77
+ traverseDir ( rootPath )
78
+
79
+ console . log ( 'Loaded Entities: ' , entities )
80
+ return entities
81
+ }
82
+ }
0 commit comments