forked from alterminal/alterminal
first commit
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// envOrTest 讀取環境變數,空值時回傳 fallback(與 store.EnvOr 同邏輯;
|
||||
// 測試不可匯入 internal/store——其 AutoMigrate 匯入本套件,會形成測試循環)。
|
||||
func envOrTest(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// openTestDB 連線 DB_* 環境變數指定的資料庫並遷移 users、sessions 資料表,
|
||||
// 供 login/logout 整合測試使用(測試自行建立資料並於 t.Cleanup 清理)。
|
||||
func openTestDB() (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable TimeZone=UTC",
|
||||
envOrTest("DB_HOST", "localhost"),
|
||||
envOrTest("DB_PORT", "5432"),
|
||||
envOrTest("DB_USER", "postgres"),
|
||||
envOrTest("DB_PASSWORD", "postgres"),
|
||||
envOrTest("DB_NAME", "alterminal"),
|
||||
)
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := db.AutoMigrate(&User{}, &Session{}); err != nil {
|
||||
return nil, fmt.Errorf("auto migrate: %w", err)
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
Reference in New Issue
Block a user