lens @ cd1fa849fb161d3bbc7c582aa2787315a1037db1

 1package view
 2
 3import (
 4	"github.com/valyala/fasthttp"
 5
 6	"git.sr.ht/~gabrielgio/img"
 7	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
 8	"git.sr.ht/~gabrielgio/img/pkg/ext"
 9)
10
11type (
12	SettingsView struct {
13		// there is not need to create a controller for this
14		settingsRepository repository.SettingsRepository
15		userRepository     repository.UserRepository
16	}
17
18	SettingsPage struct {
19		Settings *repository.Settings
20		Users    []*repository.User
21	}
22)
23
24func NewSettingsView(
25	settingsRespository repository.SettingsRepository,
26	userRepository repository.UserRepository,
27) *SettingsView {
28	return &SettingsView{
29		settingsRepository: settingsRespository,
30		userRepository:     userRepository,
31	}
32}
33
34func (self *SettingsView) Index(ctx *fasthttp.RequestCtx) error {
35	s, err := self.settingsRepository.Load(ctx)
36	if err != nil {
37		return err
38	}
39
40	users, err := self.userRepository.List(ctx)
41	if err != nil {
42		return err
43	}
44
45	return img.Render(ctx, "settings.html", &img.HTMLView[*SettingsPage]{
46		Title: "Settings",
47		Data: &SettingsPage{
48			Settings: s,
49			Users:    users,
50		},
51	})
52}
53
54func (self *SettingsView) Save(ctx *fasthttp.RequestCtx) error {
55	var (
56		showMode  = string(ctx.FormValue("showMode")) == "on"
57		showOwner = string(ctx.FormValue("showOwner")) == "on"
58	)
59
60	err := self.settingsRepository.Save(ctx, &repository.Settings{
61		ShowMode:  showMode,
62		ShowOwner: showOwner,
63	})
64	if err != nil {
65		return err
66	}
67
68	return self.Index(ctx)
69}
70
71func (self *SettingsView) SetMyselfIn(r *ext.Router) {
72	r.GET("/settings/", self.Index)
73	r.POST("/settings/", self.Save)
74}