From 473052ed8f2c83052ed5b47a7f4cec68ac2621a6 Mon Sep 17 00:00:00 2001
From: xengineering <me@xengineering.eu>
Date: Sun, 13 Oct 2024 19:52:28 +0200
Subject: model: Replace global db variable by custom type

Reducing global variables makes it easier to understand functions
independently of the rest of the code.

Adding the new model.DB type as a custom variant of the sql.DB type
makes it possible to write methods for the database which makes the code
way more readable.
---
 server.go | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)

(limited to 'server.go')

diff --git a/server.go b/server.go
index 7caf328..0c26188 100644
--- a/server.go
+++ b/server.go
@@ -7,6 +7,7 @@ import (
 	"net/http"
 
 	"xengineering.eu/ceres/controller"
+	"xengineering.eu/ceres/model"
 	"xengineering.eu/ceres/view"
 
 	"github.com/gorilla/mux"
@@ -19,7 +20,7 @@ type Server struct {
 //go:embed view/static/simple.css/simple.css view/static/ceres.js
 var static embed.FS
 
-func NewServer(addr string) Server {
+func NewServer(addr string, db *model.DB) Server {
 	var r *mux.Router = mux.NewRouter()
 
 	r.PathPrefix("/static/").
@@ -27,13 +28,13 @@ func NewServer(addr string) Server {
 
 	r.HandleFunc("/version", view.VersionRead(version)).Methods(`GET`)
 
-	r.HandleFunc("/recipes", view.RecipesRead).Methods(`GET`)
+	r.HandleFunc("/recipes", view.RecipesRead(db)).Methods(`GET`)
 	r.HandleFunc("/recipe/create", view.RecipeCreate).Methods(`GET`)
 
-	r.HandleFunc("/recipe", controller.RecipeCreate).Methods(`POST`)
-	r.HandleFunc("/recipe/{id:[0-9]+}", view.RecipeRead).Methods(`GET`)
-	r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeUpdate).Methods(`POST`)
-	r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeDelete).Methods(`DELETE`)
+	r.HandleFunc("/recipe", controller.RecipeCreate(db)).Methods(`POST`)
+	r.HandleFunc("/recipe/{id:[0-9]+}", view.RecipeRead(db)).Methods(`GET`)
+	r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeUpdate(db)).Methods(`POST`)
+	r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeDelete(db)).Methods(`DELETE`)
 
 	r.HandleFunc("/favicon.ico", view.FaviconRead).Methods(`GET`)
 
-- 
cgit v1.2.3-70-g09d2