Skip to content

Commit

Permalink
MealLog testing
Browse files Browse the repository at this point in the history
  • Loading branch information
szabolcs-horvath committed Dec 23, 2024
1 parent ad5cc71 commit 4a85ea2
Show file tree
Hide file tree
Showing 8 changed files with 188 additions and 42 deletions.
5 changes: 1 addition & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@ module github.com/szabolcs-horvath/nutrition-tracker
go 1.23.1

require (
github.com/auth0/go-jwt-middleware/v2 v2.2.2
github.com/google/uuid v1.6.0
github.com/joho/godotenv v1.5.1
github.com/mattn/go-sqlite3 v1.14.24
)

require github.com/donseba/go-htmx v1.12.0

require github.com/auth0/go-jwt-middleware/v2 v2.2.2

require (
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/sync v0.10.0 // indirect
Expand Down
8 changes: 0 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ github.com/auth0/go-jwt-middleware/v2 v2.2.2 h1:vrvkFZf72r3Qbt45KLjBG3/6Xq2r3NTi
github.com/auth0/go-jwt-middleware/v2 v2.2.2/go.mod h1:4vwxpVtu/Kl4c4HskT+gFLjq0dra8F1joxzamrje6J0=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/donseba/go-htmx v1.11.3 h1:YW1JiKImneilQ73r+8xnoTlftlxt2Rh9L3IoZSa5iXk=
github.com/donseba/go-htmx v1.11.3/go.mod h1:8PTAYvNKf8+QYis+DpAsggKz+sa2qljtMgvdAeNBh5s=
github.com/donseba/go-htmx v1.12.0 h1:7tESER0uxaqsuGMv3yP3pK1drfBUXM6apG4H7/3+IgE=
github.com/donseba/go-htmx v1.12.0/go.mod h1:8PTAYvNKf8+QYis+DpAsggKz+sa2qljtMgvdAeNBh5s=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
Expand All @@ -18,12 +14,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
gopkg.in/go-jose/go-jose.v2 v2.6.3 h1:nt80fvSDlhKWQgSWyHyy5CfmlQr+asih51R8PTWNKKs=
Expand Down
34 changes: 34 additions & 0 deletions http_server/routes/api/v1/meallogs/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package meallogs

import (
"encoding/json"
"github.com/szabolcs-horvath/nutrition-tracker/repository"
"github.com/szabolcs-horvath/nutrition-tracker/util"
"net/http"
)

const Prefix = "/meallogs"

func Handlers() map[string]http.HandlerFunc {
return map[string]http.HandlerFunc{
"POST /": createHandler,
//"PUT /": updateHandler,
//"DELETE /{id}": deleteHandler,
}
}

func createHandler(w http.ResponseWriter, r *http.Request) {
var requestItem *repository.MealLog
if err := json.NewDecoder(r.Body).Decode(requestItem); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
item, err := repository.CreateMealLog(r.Context(), requestItem)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = util.WriteJson(w, http.StatusCreated, item); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
2 changes: 2 additions & 0 deletions http_server/routes/api/v1/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package v1
import (
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes/api/v1/items"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes/api/v1/meallogs"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes/api/v1/notifications"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes/api/v1/portions"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes/api/v1/users"
Expand All @@ -17,5 +18,6 @@ func Routes() map[string]*http.ServeMux {
items.Prefix: routes.SubRouteHandlers(items.Handlers()),
portions.Prefix: routes.SubRouteHandlers(portions.Handlers()),
notifications.Prefix: routes.SubRouteHandlers(notifications.Handlers()),
meallogs.Prefix: routes.SubRouteHandlers(meallogs.Handlers()),
}
}
84 changes: 59 additions & 25 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package main

import (
"context"
"github.com/donseba/go-htmx"
"github.com/joho/godotenv"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/middleware"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes"
"github.com/szabolcs-horvath/nutrition-tracker/http_server/routes/api"
"github.com/szabolcs-horvath/nutrition-tracker/repository"
"github.com/szabolcs-horvath/nutrition-tracker/util"
"html/template"
"io"
"log/slog"
"net/http"
"os"
Expand All @@ -16,9 +18,42 @@ import (
"time"
)

type Templates struct {
templates *template.Template
}

type App struct {
HTMX *htmx.HTMX
Router *http.ServeMux
Router *http.ServeMux
Templates *Templates
}

func (app App) Render(w io.Writer, name string, data interface{}) error {
return app.Templates.templates.ExecuteTemplate(w, name, data)
}

func newApp() *App {
return &App{
Router: http.NewServeMux(),
Templates: &Templates{
templates: template.Must(template.ParseGlob("templates/*.html")),
},
}
}

func getEnvFile() string {
envFile := ".env"
if len(os.Args[1:]) > 0 {
if os.Args[1] != "" {
envFile = os.Args[1]
}
}
slog.Info("[getEnvFile] Using .env file: " + envFile)
return envFile
}

type IndexData struct {
MealLogs []*repository.MealLog
Items []*repository.Item
}

func main() {
Expand All @@ -28,21 +63,31 @@ func main() {
panic(1)
}

app := &App{
HTMX: htmx.New(),
Router: http.NewServeMux(),
}

app := newApp()
routes.ServeRoute(app.Router, api.Prefix, api.Routes())

app.Router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
h := app.HTMX.NewHandler(w, r)
fs := http.FileServer(http.Dir("web/static/vendor"))
app.Router.Handle("/static/", http.StripPrefix("/static/", fs))

page := htmx.NewComponent("templates/index.html")
app.Router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
mealLogs, err := repository.FindMealLogsForUserAndDate(r.Context(), 1)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
items, err := repository.ListItems(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

_, err := h.Render(r.Context(), page)
data := IndexData{
MealLogs: mealLogs,
Items: items,
}
err = app.Render(w, "index", data)
if err != nil {
slog.ErrorContext(r.Context(), "Error rendering index.html")
http.Error(w, err.Error(), http.StatusBadRequest)
}
})

Expand All @@ -60,7 +105,7 @@ func main() {
go func() {
slog.Info("[main] Starting server on address " + server.Addr)
if err := server.ListenAndServe(); err != nil {
slog.Error("[main] Failed to serve address "+server.Addr, "ERROR", err)
slog.Info("[main] Stopped serving address "+server.Addr, "ERROR", err)
}
slog.Info("[main] Stopped serving new connections on address " + server.Addr)
}()
Expand All @@ -75,14 +120,3 @@ func main() {
}
slog.Info("[main] Graceful shutdown complete.")
}

func getEnvFile() string {
envFile := ".env"
if len(os.Args[1:]) > 0 {
if os.Args[1] != "" {
envFile = os.Args[1]
}
}
slog.Info("[getEnvFile] Using .env file: " + envFile)
return envFile
}
19 changes: 19 additions & 0 deletions repository/meallogs.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,25 @@ func convertMealLog(mealLog *sqlc.MealLog_sqlc) *MealLog {
}
}

func FindMealLogsForUserAndDate(ctx context.Context, ownerId int64) ([]*MealLog, error) {
queries, err := GetQueries()
if err != nil {
return nil, err
}
list, err := queries.FindMealLogsForUserAndDate(ctx, ownerId)
if err != nil {
return nil, err
}
result := make([]*MealLog, len(list))
for i, m := range list {
result[i] = convertMealLog(&m.MealLogSqlc)
result[i].Meal = convertMeal(&m.MealSqlc)
result[i].Item = convertItem(&m.ItemSqlc)
result[i].Portion = convertPortion(&m.PortionSqlc)
}
return result, nil
}

func CreateMealLog(ctx context.Context, mealLog *MealLog) (*MealLog, error) {
queries, err := GetQueries()
if err != nil {
Expand Down
66 changes: 61 additions & 5 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -1,14 +1,70 @@
{{ block "index" . }}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Nutrition Tracker</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../web/static/vendor/bootstrap/bootstrap.min.css" rel="stylesheet">
<script src="../web/static/vendor/bootstrap/bootstrap.min.js"></script>
<script src="../web/static/vendor/htmx/htmx.min.js"></script>
<link href="/static/bootstrap/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>Hello World!</h1>
<div class="container-sm">
<form hx-swap="outerHTML" hx-post="api/v1/meallogs/" hx-ext="json-enc">
mealId: <input type="number" name="Meal" required>
itemId: <input type="number" name="Item" required>
portionId: <input type="number" name="Portion" required>
count: <input type="number" name="PortionMultiplier" required>
dateTime: <input type="datetime-local" name="DateTime" required>
<button type="submit">Add</button>
</form>
<hr/>
{{ template "meallogs" .MealLogs }}
<hr/>
{{ template "items" .Items }}
</div>
<script src="/static/bootstrap/bootstrap.bundle.min.js"></script>
<script src="/static/htmx/htmx.min.js"></script>
<script src="/static/htmx/extensions/json-enc.js"></script>
</body>
</html>
</html>
{{ end }}

{{ block "meallogs" . }}
<ol>
{{ range . }}
<li>
<span>{{ .DateTime }}</span>
<span>Calories: {{ .GetCalories }}</span>
</li>
{{ end }}
</ol>
{{ end }}

{{ block "items" . }}
<table class="table table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Liquid</th>
<th scope="col">Calories</th>
<th scope="col">Fats</th>
<th scope="col">Carbs</th>
<th scope="col">Proteins</th>
</tr>
</thead>
<tbody>
{{ range . }}
<tr>
<td>{{ .ID }}</td>
<td>{{ .Name }}</td>
<td>{{ .Liquid }}</td>
<td>{{ .CaloriesPer100 }}</td>
<td>{{ .FatsPer100 }}</td>
<td>{{ .CarbsPer100 }}</td>
<td>{{ .ProteinsPer100 }}</td>
</tr>
{{ end }}
</tbody>
</table>
{{ end }}
12 changes: 12 additions & 0 deletions web/static/vendor/htmx/extensions/json-enc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
htmx.defineExtension('json-enc', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['Content-Type'] = "application/json";
}
},

encodeParameters : function(xhr, parameters, elt) {
xhr.overrideMimeType('text/json');
return (JSON.stringify(parameters));
}
});

0 comments on commit 4a85ea2

Please sign in to comment.