lens @ 249ee195ce52ee4a4defeb67a33ef353919d3a11

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