73 lines
2.4 KiB
Go
73 lines
2.4 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"primaya-api/cpone-middleware/internal/databaseconfig"
|
|
)
|
|
|
|
type DatabaseSettingsStore interface {
|
|
List() []databaseconfig.PublicSetting
|
|
Get(code string) (databaseconfig.PublicSetting, bool)
|
|
Upsert(ctx context.Context, setting databaseconfig.Setting) (databaseconfig.PublicSetting, bool, error)
|
|
}
|
|
|
|
type DatabaseSettingsHandler struct{ store DatabaseSettingsStore }
|
|
|
|
func NewDatabaseSettingsHandler(store DatabaseSettingsStore) DatabaseSettingsHandler {
|
|
return DatabaseSettingsHandler{store: store}
|
|
}
|
|
|
|
func (h DatabaseSettingsHandler) List(w http.ResponseWriter, _ *http.Request) {
|
|
WriteJSON(w, http.StatusOK, Response{Success: true, Message: "ok", Data: h.store.List()})
|
|
}
|
|
|
|
func (h DatabaseSettingsHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|
setting, found := h.store.Get(r.PathValue("kodeRs"))
|
|
if !found {
|
|
WriteJSON(w, http.StatusNotFound, Response{Success: false, Message: "Setting database tidak ditemukan", Data: nil})
|
|
return
|
|
}
|
|
WriteJSON(w, http.StatusOK, Response{Success: true, Message: "ok", Data: setting})
|
|
}
|
|
|
|
func (h DatabaseSettingsHandler) Store(w http.ResponseWriter, r *http.Request) {
|
|
var payload databaseconfig.Setting
|
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(&payload); err != nil {
|
|
WriteJSON(w, http.StatusUnprocessableEntity, Response{Success: false, Message: "Payload JSON tidak valid: " + err.Error(), Data: nil})
|
|
return
|
|
}
|
|
if err := databaseconfig.Validate(payload); err != nil {
|
|
WriteJSON(w, http.StatusUnprocessableEntity, Response{Success: false, Message: err.Error(), Data: nil})
|
|
return
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
setting, created, err := h.store.Upsert(ctx, payload)
|
|
if err != nil {
|
|
status := http.StatusInternalServerError
|
|
message := "Gagal menyimpan setting database"
|
|
if errors.Is(err, context.DeadlineExceeded) || strings.Contains(err.Error(), "koneksi database") {
|
|
status = http.StatusBadGateway
|
|
message = err.Error()
|
|
}
|
|
WriteJSON(w, status, Response{Success: false, Message: message, Data: nil})
|
|
return
|
|
}
|
|
status := http.StatusOK
|
|
message := "Setting database berhasil diperbarui"
|
|
if created {
|
|
status = http.StatusCreated
|
|
message = "Setting database berhasil ditambahkan"
|
|
}
|
|
WriteJSON(w, status, Response{Success: true, Message: message, Data: setting})
|
|
}
|