在使用 Nx monorepo 開發 NestJS 後端並搭配 TypeORM 連接資料庫的過程中,我遇到了一個奇怪的問題。不管我如何調整 TypeORM 的配置,只要在 app.module.ts 中注入 TypeOrmModule.forRoot(typeOrmConfig),前端的 API 接口就會卡在 “dependencies initialized loading” 的畫面無法正常顯示。經過一段時間的研究後,我終於找到解決方法,現在我想與大家分享。
首先,問題出在 TypeOrmConfig 的 entities 路徑設定上。如果只給它一個 Array,TypeORM 的連接就會一直等待,而你的 API endpoint 就無法正常運作。
export const typeOrmConfig: TypeOrmModuleOptions = {
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'pass',
database: 'mydb',
synchronize: true,
entities: ['../**/*.entity.ts'] <--- 這段是雷
}
後來我嘗試在路徑前面加上 __dirname,變成以下程式碼:
export const typeOrmConfig: TypeOrmModuleOptions = {
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'pass',
database: 'mydb',
synchronize: true,
entities: [__dirname + '../**/*.entity.ts'] <--- 這在 Nx 會變成二段雷
}
然而,這又引發了另一個問題,Nx 找不到相對路徑,輸出的路徑類似於 “../your-app/dist/api/..”。我在以下兩個 GitHub 連結中提出了這個問題:
https://github.com/nrwl/nx/issues/3898
https://github.com/nrwl/nx/issues/2842
最後,我使用了 autoLoadEntities: true 這個設定來解決問題。但需要在子功能中注入 TypeOrmModule.forFeature([FeautreEntity])
。
最終的 TypeOrmConfig 配置如下:
export const typeOrmConfig: TypeOrmModuleOptions = {
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'pass',
database: 'mydb',
synchronize: true,
autoLoadEntities: true
}
問題終於解決了!以上是我遇到的問題及解決方法,希望對其他可能遇到相同問題的人有所幫助。