From 64496464b3812839c1e4b440bdf69cc84f39c491 Mon Sep 17 00:00:00 2001 From: "Gabriel A. Giovanini" Date: Wed, 15 Jun 2022 12:40:12 +0200 Subject: ref: Move to a MVC like approach Before everything was dumped into the controller file, now it is spread out a bit. It is still far from good, like the controller is not really a controller... baby steps I guess The refactored was based on this post: https://www.alexedwards.net/blog/organising-database-access --- db/db.go | 2 +- db/model.go | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) (limited to 'db') diff --git a/db/db.go b/db/db.go index 128dcc8..5c904fd 100644 --- a/db/db.go +++ b/db/db.go @@ -17,5 +17,5 @@ func ConnectDb() { panic("failed to connect to the database.") } - DB.AutoMigrate(&YdlEntry{}) + DB.AutoMigrate(&Entry{}) } diff --git a/db/model.go b/db/model.go index 6f35cd0..4b814f9 100644 --- a/db/model.go +++ b/db/model.go @@ -1,11 +1,42 @@ package db -import "gorm.io/gorm" +import ( + "gorm.io/gorm" +) -type YdlEntry struct { +type Entry struct { gorm.Model Title string Link string Format string OutputFolder string } + +type EntryModel struct { + DB *gorm.DB +} + +func (m EntryModel) Find(id string) Entry { + var entry Entry + where := "id = " + id + m.DB.Where(where).FirstOrInit(&entry) + return entry +} + +func (m EntryModel) All() []Entry { + var entries []Entry + m.DB.Find(&entries) + return entries +} + +func (m EntryModel) Create(entry Entry) { + m.DB.Create(&entry) +} + +func (m EntryModel) Update(entry Entry) { + m.DB.Save(&entry) +} + +func (m EntryModel) Delete(id string) { + m.DB.Delete(&Entry{}, id) +} -- cgit v1.2.3