@@ -5,7 +5,7 @@ const prisma = new PrismaClient({
55 { level : "warn" , emit : "event" } ,
66 { level : "info" , emit : "event" } ,
77 { level : "error" , emit : "event" } ,
8- ] ,
8+ } ,
99} ) ;
1010
1111prisma . $on ( "warn" , ( e ) => {
@@ -20,17 +20,53 @@ prisma.$on("error", (e) => {
2020 // console.log("Prisma Error:", e);
2121} ) ;
2222
23- // Check if Prisma connection is successful
24- ( async ( ) => {
25- try {
26- console . log ( "Checking Prisma connection..." ) ;
27- await prisma . $connect ( ) ;
28- await prisma . rote . findFirst ( ) ;
29- console . log ( "Prisma connected successfully!" ) ;
30- } catch ( error ) {
31- console . info ( "Failed to connect to Prisma." , error ) ;
32- process . exit ( 1 ) ; // 如果连接失败,终止进程
23+ /**
24+ * 等待数据库连接就绪,带重试机制
25+ * @param maxRetries 最大重试次数,默认 30 次
26+ * @param retryDelay 重试延迟(毫秒),默认 2 秒
27+ */
28+ export async function waitForDatabase (
29+ maxRetries : number = 30 ,
30+ retryDelay : number = 2000
31+ ) : Promise < void > {
32+ for ( let attempt = 1 ; attempt <= maxRetries ; attempt ++ ) {
33+ try {
34+ console . log ( `🔄 Attempting to connect to database (${ attempt } /${ maxRetries } )...` ) ;
35+
36+ // 如果之前有连接尝试,先断开
37+ try {
38+ await prisma . $disconnect ( ) ;
39+ } catch {
40+ // 忽略断开连接的错误
41+ }
42+
43+ // 尝试连接
44+ await prisma . $connect ( ) ;
45+
46+ // 尝试执行一个简单的查询来验证连接
47+ await prisma . $queryRaw `SELECT 1` ;
48+ console . log ( "✅ Prisma connected successfully!" ) ;
49+ return ;
50+ } catch ( error : any ) {
51+ // 确保在错误时断开连接
52+ try {
53+ await prisma . $disconnect ( ) ;
54+ } catch {
55+ // 忽略断开连接的错误
56+ }
57+
58+ if ( attempt === maxRetries ) {
59+ console . error ( "❌ Failed to connect to database after all retries:" , error ) ;
60+ throw new Error (
61+ `Database connection failed after ${ maxRetries } attempts. Please check your database configuration. Error: ${ error ?. message || error } `
62+ ) ;
63+ }
64+ console . log (
65+ `⏳ Database not ready yet, retrying in ${ retryDelay / 1000 } s... (${ attempt } /${ maxRetries } )`
66+ ) ;
67+ await new Promise ( ( resolve ) => setTimeout ( resolve , retryDelay ) ) ;
68+ }
3369 }
34- } ) ( ) ;
70+ }
3571
3672export default prisma ;
0 commit comments