89 lines
2.5 KiB
Go
89 lines
2.5 KiB
Go
package settings
|
|
|
|
import (
|
|
"encoding/json"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
|
|
"lst.net/pkg/logger"
|
|
)
|
|
|
|
func RegisterSettingsRoutes(l *gin.Engine, baseUrl string, log *logger.CustomLogger, db *gorm.DB) {
|
|
// seed the db on start up
|
|
SeedSettings(db, log)
|
|
|
|
s := l.Group(baseUrl + "/api/v1")
|
|
s.GET("/settings", func(c *gin.Context) { getSettings(c, log, db) })
|
|
s.PATCH("/settings/:id", func(c *gin.Context) { updateSettingById(c, log, db) })
|
|
}
|
|
|
|
func getSettings(c *gin.Context, log *logger.CustomLogger, db *gorm.DB) {
|
|
configs, err := GetAllSettings(db)
|
|
log.Info("Current Settings", "settings", map[string]interface{}{
|
|
"endpoint": "/api/v1/settings",
|
|
"client_ip": c.ClientIP(),
|
|
"user_agent": c.Request.UserAgent(),
|
|
})
|
|
|
|
if err != nil {
|
|
log := logger.New()
|
|
log.Error("Current Settings", "settings", map[string]interface{}{
|
|
"endpoint": "/api/v1/settings",
|
|
"client_ip": c.ClientIP(),
|
|
"user_agent": c.Request.UserAgent(),
|
|
"error": err,
|
|
})
|
|
c.JSON(500, gin.H{"message": "There was an error getting the settings", "error": err})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, gin.H{"message": "Current settings", "data": configs})
|
|
}
|
|
|
|
func updateSettingById(c *gin.Context, log *logger.CustomLogger, db *gorm.DB) {
|
|
|
|
settingID := c.Param("id")
|
|
|
|
if settingID == "" {
|
|
c.JSON(500, gin.H{"message": "Invalid data"})
|
|
log.Error("Invalid data", "settings", map[string]interface{}{
|
|
"endpoint": "/api/v1/settings",
|
|
"client_ip": c.ClientIP(),
|
|
"user_agent": c.Request.UserAgent(),
|
|
})
|
|
return
|
|
}
|
|
var setting SettingUpdateInput
|
|
|
|
//err := c.ShouldBindBodyWithJSON(&setting)
|
|
|
|
decoder := json.NewDecoder(c.Request.Body) // more strict and will force us to have correct data
|
|
decoder.DisallowUnknownFields()
|
|
|
|
if err := decoder.Decode(&setting); err != nil {
|
|
c.JSON(400, gin.H{"message": "Invalid request body", "error": err.Error()})
|
|
log.Error("Invalid request body", "settings", map[string]interface{}{
|
|
"endpoint": "/api/v1/settings",
|
|
"client_ip": c.ClientIP(),
|
|
"user_agent": c.Request.UserAgent(),
|
|
"error": err,
|
|
})
|
|
return
|
|
}
|
|
|
|
if err := UpdateSetting(log, db, settingID, setting); err != nil {
|
|
c.JSON(500, gin.H{"message": "Failed to update setting", "error": err.Error()})
|
|
log.Error("Failed to update setting", "settings", map[string]interface{}{
|
|
"endpoint": "/api/v1/settings",
|
|
"client_ip": c.ClientIP(),
|
|
"user_agent": c.Request.UserAgent(),
|
|
"error": err,
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, gin.H{"message": "Setting was just updated", "data": setting})
|
|
|
|
}
|