diff options
author | Santo Cariotti <santo@dcariotti.me> | 2025-04-02 19:31:12 +0200 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2025-04-02 19:37:12 +0200 |
commit | a9b84f3f3b1d92335188d43048587e32e0921079 (patch) | |
tree | a4313f7660a99745d7d5da4d92dc9509d0dbe35e /api/database | |
parent | 2e92ccd66eb5c31b8fbbcd205d7b4a882450e9d0 (diff) |
Init login and frontend
Diffstat (limited to 'api/database')
-rw-r--r-- | api/database/database.go | 32 | ||||
-rw-r--r-- | api/database/models.go | 11 |
2 files changed, 43 insertions, 0 deletions
diff --git a/api/database/database.go b/api/database/database.go new file mode 100644 index 0000000..e5ecca8 --- /dev/null +++ b/api/database/database.go @@ -0,0 +1,32 @@ +package database + +import ( + "gorm.io/driver/postgres" + "gorm.io/gorm" + + "errors" +) + +// Global variable but private +var db *gorm.DB = nil + +// Init the database from a DSN string which must be a valid PostgreSQL dsn. +// Also, auto migrate all the models. +func InitDb(dsn string) (*gorm.DB, error) { + var err error + db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) + + if err == nil { + db.AutoMigrate(&User{}) + } + + return db, err +} + +// Return the instance or error if the config is not laoded yet +func GetDb() (*gorm.DB, error) { + if db == nil { + return nil, errors.New("You must call `InitDb()` first.") + } + return db, nil +} diff --git a/api/database/models.go b/api/database/models.go new file mode 100644 index 0000000..e309a36 --- /dev/null +++ b/api/database/models.go @@ -0,0 +1,11 @@ +package database + +import "time" + +type User struct { + ID int `json:"id"` + Username string `json:"username"` + Password string `json:"password"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} |