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 --- controller/controller.go | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) (limited to 'controller') diff --git a/controller/controller.go b/controller/controller.go index ffa89ce..252be73 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -10,6 +10,10 @@ import ( "github.com/gin-gonic/gin" ) +type Env struct { + Entries db.EntryModel +} + func spawnWorker(link string, output string) { work.Submit(func(ctx context.Context) error { yt.RunYtDlpProcess(link, output) @@ -17,38 +21,35 @@ func spawnWorker(link string, output string) { }) } -func GetEntries(c *gin.Context) { - var entries []db.YdlEntry - db.DB.Find(&entries) +func (e Env) GetEntries(c *gin.Context) { + entries := e.Entries.All() c.HTML(http.StatusOK, "index", entries) } -func GetEntry(c *gin.Context) { - var entry db.YdlEntry +func (e *Env) GetEntry(c *gin.Context) { id := c.Param("id") - where := "id = " + id - db.DB.Where(where).FirstOrInit(&entry) + entry := e.Entries.Find(id) c.HTML(http.StatusOK, "entry", entry) } -func UpdateEntry(c *gin.Context) { - var entry db.YdlEntry +func (e *Env) UpdateEntry(c *gin.Context) { + var entry db.Entry c.ShouldBind(&entry) - db.DB.Save(&entry) - c.HTML(http.StatusOK, "entry", entry) + e.Entries.Update(entry) + c.Redirect(http.StatusFound, "/") } -func CreateEntry(c *gin.Context) { - var entry db.YdlEntry +func (e *Env) CreateEntry(c *gin.Context) { + var entry db.Entry c.ShouldBind(&entry) - db.DB.Create(&entry) + e.Entries.Create(entry) spawnWorker(entry.Link, entry.OutputFolder) c.Redirect(http.StatusFound, "/") } -func DeleteEntry(c *gin.Context) { - var entry db.YdlEntry +func (e *Env) DeleteEntry(c *gin.Context) { + var entry db.Entry id := c.Param("id") - db.DB.Delete(&entry, id) + e.Entries.Delete(id) c.HTML(http.StatusOK, "entry", entry) } -- cgit v1.2.3