81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package logger
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"github.com/FrankenBotDev/FrankenAPI/ent"
|
|
"github.com/FrankenBotDev/FrankenAPI/ent/logging"
|
|
"github.com/FrankenBotDev/FrankenAPI/pkg/sys"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
func LogRouter() http.Handler {
|
|
r := chi.NewRouter()
|
|
|
|
r.Get("/", getapilog)
|
|
r.Post("/", apilogger)
|
|
return r
|
|
}
|
|
|
|
func apilogger(w http.ResponseWriter, r *http.Request) {
|
|
logJson := make(map[string]string)
|
|
logData, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, `{"type":"error", "code":"request_data_could_not_be_proccessed"}`, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
err = json.Unmarshal(logData, &logJson)
|
|
if err != nil {
|
|
http.Error(w, `{"type":"error", "code":"request_data_could_not_be_proccessed"}`, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
err = Logtodb([]string{logJson["commiterid"], logJson["description"], logJson["actiontype"], logJson["serverid"]}, r.Context().Value(sys.EntClientKey).(*ent.Client), r.Context().Value(sys.ContextClientKey).(context.Context))
|
|
if err != nil {
|
|
http.Error(w, `{"type":"error", "code":"could_not_create_log_in_database"}`, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Write([]byte(`{"type":"success", "code":"log_added_to_database"}`))
|
|
}
|
|
|
|
func getapilog(w http.ResponseWriter, r *http.Request) {
|
|
loggerRequest := r.URL.Query()
|
|
|
|
log, err := r.Context().Value(sys.EntClientKey).(*ent.Client).Logging.Query().
|
|
Where(logging.Serverid(loggerRequest.Get("serverid"))).
|
|
Order(ent.Desc(logging.FieldID)).
|
|
All(r.Context().Value(sys.ContextClientKey).(context.Context))
|
|
if err != nil {
|
|
sys.ErrorJsonResponse(w, "request_data_could_not_found_or_fetched", err)
|
|
return
|
|
}
|
|
|
|
sys.SuccessJsonResponse(w, log)
|
|
}
|
|
|
|
// logs a given message array to the database
|
|
// message args
|
|
// 0 -> commiters id
|
|
// 1 -> description
|
|
// 2 -> action type
|
|
// 3 -> the server logged on
|
|
func Logtodb(message []string, client *ent.Client, context context.Context) error {
|
|
err := client.Logging.Create().
|
|
SetCommiter(message[0]).
|
|
SetDescription(message[1]).
|
|
SetType(message[2]).
|
|
SetServerid(message[3]).
|
|
Exec(context)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|