diff --git a/cmd/main.go b/cmd/main.go index 64ef52e..79ef689 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -16,10 +16,15 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/joho/godotenv" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/handler/api" "github.com/mstgnz/cronjob/handler/web" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/auth" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/load" + "github.com/mstgnz/cronjob/pkg/logger" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" "github.com/mstgnz/cronjob/schedule" ) @@ -48,17 +53,17 @@ var ( func init() { // Load Env if err := godotenv.Load(".env"); err != nil { - config.App().Log.Warn(fmt.Sprintf("Load Env Error: %v", err)) + logger.Warn(fmt.Sprintf("Load Env Error: %v", err)) log.Fatalf("Load Env Error: %v", err) } // init conf _ = config.App() - config.CustomValidate() + validate.CustomValidate() // Load Sql config.App().QUERY = make(map[string]string) - if query, err := config.LoadSQLQueries(); err != nil { - config.App().Log.Warn(fmt.Sprintf("Load Sql Error: %v", err)) + if query, err := load.LoadSQLQueries(); err != nil { + logger.Warn(fmt.Sprintf("Load Sql Error: %v", err)) log.Fatalf("Load Sql Error: %v", err) } else { config.App().QUERY = query @@ -72,7 +77,7 @@ type HttpHandler func(w http.ResponseWriter, r *http.Request) error func Catch(h HttpHandler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if err := h(w, r); err != nil { - config.App().Log.Info("HTTP Handler Error", "err", err.Error(), "path", r.URL.Path) + logger.Info("HTTP Handler Error", "err", err.Error(), "path", r.URL.Path) } } } @@ -250,7 +255,7 @@ func main() { // Not Found r.NotFound(func(w http.ResponseWriter, r *http.Request) { if strings.Contains(r.URL.Path, "api") { - _ = config.WriteJSON(w, http.StatusUnauthorized, config.Response{Status: false, Message: "Not Found"}) + _ = response.WriteJSON(w, http.StatusUnauthorized, response.Response{Status: false, Message: "Not Found"}) return } http.Redirect(w, r, "/", http.StatusSeeOther) @@ -264,17 +269,17 @@ func main() { go func() { err := http.ListenAndServe(fmt.Sprintf(":%s", PORT), r) if err != nil && err != http.ErrServerClosed { - config.App().Log.Warn("Fatal Error", "err", err.Error()) + logger.Warn("Fatal Error", "err", err.Error()) log.Fatal(err.Error()) } }() - config.App().Log.Info("Cron is running on", PORT) + logger.Info("Cron is running on", PORT) // Block until a signal is received <-ctx.Done() - config.App().Log.Info("Cron is shutting on", PORT) + logger.Info("Cron is shutting on", PORT) // set Shutting config.App().Shutting = true @@ -282,16 +287,16 @@ func main() { // check Running for { if config.App().Running <= 0 { - config.App().Log.Info("Cronjobs all done") + logger.Info("Cronjobs all done") break } else { - config.App().Log.Info(fmt.Sprintf("Currently %d active jobs in progress. pending completion...", config.App().Running)) + logger.Info(fmt.Sprintf("Currently %d active jobs in progress. pending completion...", config.App().Running)) } time.Sleep(time.Second * 5) } config.App().Cron.Stop() - config.App().Log.Info("Shutting down gracefully...") + logger.Info("Shutting down gracefully...") config.App().DB.CloseDatabase() } @@ -305,7 +310,7 @@ func webAuthMiddleware(next http.Handler) http.Handler { } token := strings.Replace(cookie.Value, "Bearer ", "", 1) - userId, err := config.GetUserIDByToken(token) + userId, err := auth.GetUserIDByToken(token) if err != nil { http.Redirect(w, r, "/login", http.StatusSeeOther) return @@ -334,20 +339,20 @@ func apiAuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("Authorization") if token == "" { - _ = config.WriteJSON(w, http.StatusUnauthorized, config.Response{Status: false, Message: "Invalid Token"}) + _ = response.WriteJSON(w, http.StatusUnauthorized, response.Response{Status: false, Message: "Invalid Token"}) return } token = strings.Replace(token, "Bearer ", "", 1) - userId, err := config.GetUserIDByToken(token) + userId, err := auth.GetUserIDByToken(token) if err != nil { - _ = config.WriteJSON(w, http.StatusUnauthorized, config.Response{Status: false, Message: err.Error()}) + _ = response.WriteJSON(w, http.StatusUnauthorized, response.Response{Status: false, Message: err.Error()}) return } user_id, err := strconv.Atoi(userId) if err != nil && user_id == 0 { - _ = config.WriteJSON(w, http.StatusUnauthorized, config.Response{Status: false, Message: err.Error()}) + _ = response.WriteJSON(w, http.StatusUnauthorized, response.Response{Status: false, Message: err.Error()}) return } @@ -355,7 +360,7 @@ func apiAuthMiddleware(next http.Handler) http.Handler { err = user.GetWithId(user_id) if err != nil { - _ = config.WriteJSON(w, http.StatusUnauthorized, config.Response{Status: false, Message: err.Error()}) + _ = response.WriteJSON(w, http.StatusUnauthorized, response.Response{Status: false, Message: err.Error()}) return } @@ -370,7 +375,7 @@ func isAuthMiddleware(next http.Handler) http.Handler { if err == nil { token := strings.Replace(cookie.Value, "Bearer ", "", 1) - _, err = config.GetUserIDByToken(token) + _, err = auth.GetUserIDByToken(token) if err == nil { http.Redirect(w, r, "/", http.StatusSeeOther) return @@ -396,7 +401,7 @@ func headerMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { checkMethod := r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" if checkMethod && r.Header.Get("Content-Type") != "application/json" { - _ = config.WriteJSON(w, http.StatusBadRequest, config.Response{Status: false, Message: "Invalid Content-Type"}) + _ = response.WriteJSON(w, http.StatusBadRequest, response.Response{Status: false, Message: "Invalid Content-Type"}) return } next.ServeHTTP(w, r) diff --git a/config/logger.go b/config/logger.go deleted file mode 100644 index 7b99efe..0000000 --- a/config/logger.go +++ /dev/null @@ -1,44 +0,0 @@ -package config - -import ( - "log/slog" - "strings" -) - -type Logger struct { - *slog.Logger -} - -func (l *Logger) logToDB(level string, message string) { - stmt, err := App().DB.Prepare(App().QUERY["APP_LOG_INSERT"]) - if err == nil { - _, _ = stmt.Exec(level, message) - } - defer func() { - _ = stmt.Close() - }() -} - -func (l *Logger) Info(message ...string) { - msg := strings.Join(message, ", ") - slog.Info(msg) - l.logToDB("INFO", msg) -} - -func (l *Logger) Error(message ...string) { - msg := strings.Join(message, ", ") - slog.Error(msg) - l.logToDB("ERROR", msg) -} - -func (l *Logger) Warn(message ...string) { - msg := strings.Join(message, ", ") - slog.Error(msg) - l.logToDB("WARNING", msg) -} - -func (l *Logger) Debug(message ...string) { - msg := strings.Join(message, ", ") - slog.Debug(msg) - l.logToDB("DEBUG", msg) -} diff --git a/go.mod b/go.mod index a6db2d0..5d9ce7b 100644 --- a/go.mod +++ b/go.mod @@ -10,12 +10,15 @@ require ( github.com/golang-jwt/jwt/v5 v5.2.1 github.com/joho/godotenv v1.5.1 github.com/lib/pq v1.10.9 + github.com/redis/go-redis/v9 v9.6.1 github.com/robfig/cron/v3 v3.0.1 golang.org/x/crypto v0.22.0 ) require ( + github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/eapache/go-resiliency v1.6.0 // indirect github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect github.com/eapache/queue v1.1.0 // indirect diff --git a/go.sum b/go.sum index 7c4f5c3..9ffd352 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,16 @@ github.com/IBM/sarama v1.43.2 h1:HABeEqRUh32z8yzY2hGB/j8mHSzC/HA9zlEjqFNCzSw= github.com/IBM/sarama v1.43.2/go.mod h1:Kyo4WkF24Z+1nz7xeVUFWIuKVV8RS3wM8mkvPKMdXFQ= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30= github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws= @@ -73,6 +81,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4= +github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/handler/api/group.go b/handler/api/group.go index d941e10..e2aa767 100644 --- a/handler/api/group.go +++ b/handler/api/group.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,21 +12,21 @@ type GroupHandler struct { } func (h *GroupHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *GroupHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *GroupHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *GroupHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/notification.go b/handler/api/notification.go index 856aaad..b42e84e 100644 --- a/handler/api/notification.go +++ b/handler/api/notification.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,26 +12,26 @@ type NotificationHandler struct { } func (h *NotificationHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotificationHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotificationHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotificationHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotificationHandler) BulkHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.BulkService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.BulkService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/notifiy_email.go b/handler/api/notifiy_email.go index c6d45e1..5ae9b88 100644 --- a/handler/api/notifiy_email.go +++ b/handler/api/notifiy_email.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,21 +12,21 @@ type NotifyEmailHandler struct { } func (h *NotifyEmailHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotifyEmailHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotifyEmailHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotifyEmailHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/notifiy_message.go b/handler/api/notifiy_message.go index 9b15989..af7865a 100644 --- a/handler/api/notifiy_message.go +++ b/handler/api/notifiy_message.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,21 +12,21 @@ type NotifyMessageHandler struct { } func (h *NotifyMessageHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotifyMessageHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotifyMessageHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *NotifyMessageHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/request.go b/handler/api/request.go index cac09a2..7cbb122 100644 --- a/handler/api/request.go +++ b/handler/api/request.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,26 +12,26 @@ type RequestHandler struct { } func (h *RequestHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHandler) BulkHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.RequestBulkService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.RequestBulkService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/request_header.go b/handler/api/request_header.go index 17a4cdc..7a7f338 100644 --- a/handler/api/request_header.go +++ b/handler/api/request_header.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,21 +12,21 @@ type RequestHeaderHandler struct { } func (h *RequestHeaderHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHeaderHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHeaderHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *RequestHeaderHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/schedule.go b/handler/api/schedule.go index 4115242..5900b6a 100644 --- a/handler/api/schedule.go +++ b/handler/api/schedule.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,31 +12,31 @@ type ScheduleHandler struct { } func (h *ScheduleHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *ScheduleHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *ScheduleHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *ScheduleHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *ScheduleHandler) LogListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.LogListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.LogListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *ScheduleHandler) BulkHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.BulkService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.BulkService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/user.go b/handler/api/user.go index d6487a1..45f3fd1 100644 --- a/handler/api/user.go +++ b/handler/api/user.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,31 +12,31 @@ type UserHandler struct { } func (h *UserHandler) LoginHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.LoginService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.LoginService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *UserHandler) RegisterHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.RegisterService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.RegisterService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *UserHandler) ProfileHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ProfileService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ProfileService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *UserHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *UserHandler) PassUpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.PassUpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.PassUpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *UserHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/api/webhook.go b/handler/api/webhook.go index 1f5c7a0..9449d7c 100644 --- a/handler/api/webhook.go +++ b/handler/api/webhook.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -12,21 +12,21 @@ type WebhookHandler struct { } func (h *WebhookHandler) ListHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.ListService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.ListService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *WebhookHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.CreateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.CreateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *WebhookHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.UpdateService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.UpdateService(w, r) + return response.WriteJSON(w, statusCode, result) } func (h *WebhookHandler) DeleteHandler(w http.ResponseWriter, r *http.Request) error { - statusCode, response := h.DeleteService(w, r) - return config.WriteJSON(w, statusCode, response) + statusCode, result := h.DeleteService(w, r) + return response.WriteJSON(w, statusCode, result) } diff --git a/handler/web/group.go b/handler/web/group.go index ea6df86..2bc8137 100644 --- a/handler/web/group.go +++ b/handler/web/group.go @@ -8,8 +8,9 @@ import ( "strings" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -24,14 +25,14 @@ func (h *GroupHandler) HomeHandler(w http.ResponseWriter, r *http.Request) error func (h *GroupHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "uid") + jsonData, err := response.ConvertStringIDsToInt(r, "uid") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -47,14 +48,14 @@ func (h *GroupHandler) CreateHandler(w http.ResponseWriter, r *http.Request) err } func (h *GroupHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "uid") + jsonData, err := response.ConvertStringIDsToInt(r, "uid") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil diff --git a/handler/web/home.go b/handler/web/home.go index 36d3965..8b22a6f 100644 --- a/handler/web/home.go +++ b/handler/web/home.go @@ -3,7 +3,7 @@ package web import ( "net/http" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -14,5 +14,5 @@ func (h *HomeHandler) HomeHandler(w http.ResponseWriter, r *http.Request) error } func (h *HomeHandler) TriggerHandler(w http.ResponseWriter, r *http.Request) error { - return config.WriteJSON(w, http.StatusOK, config.Response{Status: true, Message: "triggered", Data: nil}) + return response.WriteJSON(w, http.StatusOK, response.Response{Status: true, Message: "triggered", Data: nil}) } diff --git a/handler/web/notification.go b/handler/web/notification.go index 1988035..7e6407b 100644 --- a/handler/web/notification.go +++ b/handler/web/notification.go @@ -9,8 +9,9 @@ import ( "strings" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -26,19 +27,19 @@ func (h *NotificationHandler) HomeHandler(w http.ResponseWriter, r *http.Request } func (h *NotificationHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "is_mail") + jsonData, err = response.ConvertStringBoolsToBool(r, "is_mail") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "is_message") + jsonData, err = response.ConvertStringBoolsToBool(r, "is_message") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -124,19 +125,19 @@ func (h *NotificationHandler) EditHandler(w http.ResponseWriter, r *http.Request } func (h *NotificationHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "is_mail") + jsonData, err = response.ConvertStringBoolsToBool(r, "is_mail") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "is_message") + jsonData, err = response.ConvertStringBoolsToBool(r, "is_message") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -257,14 +258,14 @@ func (h *NotificationHandler) PaginationHandler(w http.ResponseWriter, r *http.R func (h *NotificationHandler) EmailCreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "notification_id") + jsonData, err := response.ConvertStringIDsToInt(r, "notification_id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -280,7 +281,7 @@ func (h *NotificationHandler) EmailCreateHandler(w http.ResponseWriter, r *http. } func (h *NotificationHandler) EmailUpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -446,14 +447,14 @@ func (h *NotificationHandler) EmailEditHandler(w http.ResponseWriter, r *http.Re func (h *NotificationHandler) MessageCreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "notification_id") + jsonData, err := response.ConvertStringIDsToInt(r, "notification_id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -469,7 +470,7 @@ func (h *NotificationHandler) MessageCreateHandler(w http.ResponseWriter, r *htt } func (h *NotificationHandler) MessageUpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil diff --git a/handler/web/request.go b/handler/web/request.go index 3725d76..d594fa2 100644 --- a/handler/web/request.go +++ b/handler/web/request.go @@ -9,8 +9,9 @@ import ( "strings" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -25,7 +26,7 @@ func (h *RequestHandler) HomeHandler(w http.ResponseWriter, r *http.Request) err } func (h *RequestHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -114,7 +115,7 @@ func (h *RequestHandler) EditHandler(w http.ResponseWriter, r *http.Request) err } func (h *RequestHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -234,14 +235,14 @@ func (h *RequestHandler) PaginationHandler(w http.ResponseWriter, r *http.Reques func (h *RequestHandler) HeaderCreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "request_id") + jsonData, err := response.ConvertStringIDsToInt(r, "request_id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -257,7 +258,7 @@ func (h *RequestHandler) HeaderCreateHandler(w http.ResponseWriter, r *http.Requ } func (h *RequestHandler) HeaderUpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil diff --git a/handler/web/schedule.go b/handler/web/schedule.go index 9bec194..ec42989 100644 --- a/handler/web/schedule.go +++ b/handler/web/schedule.go @@ -8,8 +8,9 @@ import ( "strings" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -29,42 +30,42 @@ func (h *ScheduleHandler) HomeHandler(w http.ResponseWriter, r *http.Request) er } func (h *ScheduleHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "group_id") + jsonData, err := response.ConvertStringIDsToInt(r, "group_id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringIDsToInt(r, "request_id") + jsonData, err = response.ConvertStringIDsToInt(r, "request_id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringIDsToInt(r, "notification_id") + jsonData, err = response.ConvertStringIDsToInt(r, "notification_id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringIDsToInt(r, "timeout") + jsonData, err = response.ConvertStringIDsToInt(r, "timeout") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringIDsToInt(r, "retries") + jsonData, err = response.ConvertStringIDsToInt(r, "retries") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -133,21 +134,21 @@ func (h *ScheduleHandler) EditHandler(w http.ResponseWriter, r *http.Request) er } func (h *ScheduleHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "timeout") + jsonData, err := response.ConvertStringIDsToInt(r, "timeout") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringIDsToInt(r, "retries") + jsonData, err = response.ConvertStringIDsToInt(r, "retries") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil } r.Body = io.NopCloser(strings.NewReader(string(jsonData))) - jsonData, err = config.ConvertStringBoolsToBool(r, "active") + jsonData, err = response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil diff --git a/handler/web/setting.go b/handler/web/setting.go index c08f616..364f335 100644 --- a/handler/web/setting.go +++ b/handler/web/setting.go @@ -7,8 +7,9 @@ import ( "net/http" "strings" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -53,13 +54,13 @@ func (h *SettingHandler) UsersHandler(w http.ResponseWriter, r *http.Request) er data["users"] = users w.Header().Set("Content-Type", "application/json") - result := config.MaptoJSON(data) + result := response.MaptoJSON(data) _, _ = w.Write(result) return nil } func (h *SettingHandler) UserChangeProfileHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "id") + jsonData, err := response.ConvertStringIDsToInt(r, "id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -76,7 +77,7 @@ func (h *SettingHandler) UserChangeProfileHandler(w http.ResponseWriter, r *http } func (h *SettingHandler) UserChangePasswordHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringIDsToInt(r, "id") + jsonData, err := response.ConvertStringIDsToInt(r, "id") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil diff --git a/handler/web/webhook.go b/handler/web/webhook.go index c802e3e..e6801e8 100644 --- a/handler/web/webhook.go +++ b/handler/web/webhook.go @@ -9,8 +9,9 @@ import ( "strings" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" "github.com/mstgnz/cronjob/services" ) @@ -23,7 +24,7 @@ func (h *WebhookHandler) HomeHandler(w http.ResponseWriter, r *http.Request) err } func (h *WebhookHandler) CreateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil @@ -105,7 +106,7 @@ func (h *WebhookHandler) EditHandler(w http.ResponseWriter, r *http.Request) err } func (h *WebhookHandler) UpdateHandler(w http.ResponseWriter, r *http.Request) error { - jsonData, err := config.ConvertStringBoolsToBool(r, "active") + jsonData, err := response.ConvertStringBoolsToBool(r, "active") if err != nil { _, _ = w.Write([]byte(err.Error())) return nil diff --git a/models/app_log.go b/models/app_log.go index a179e3c..aeaafbe 100644 --- a/models/app_log.go +++ b/models/app_log.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type AppLog struct { diff --git a/models/group.go b/models/group.go index c167026..f385593 100644 --- a/models/group.go +++ b/models/group.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type Group struct { diff --git a/models/notification.go b/models/notification.go index 16be8b7..b892940 100644 --- a/models/notification.go +++ b/models/notification.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type Notification struct { diff --git a/models/notify_email.go b/models/notify_email.go index bd2dc14..b6fba6c 100644 --- a/models/notify_email.go +++ b/models/notify_email.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type NotifyEmail struct { diff --git a/models/notify_message.go b/models/notify_message.go index 0b337e2..692057a 100644 --- a/models/notify_message.go +++ b/models/notify_message.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type NotifyMessage struct { diff --git a/models/request.go b/models/request.go index bdded5d..43e1f16 100644 --- a/models/request.go +++ b/models/request.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type Request struct { diff --git a/models/request_header.go b/models/request_header.go index c47d486..52b0ba9 100644 --- a/models/request_header.go +++ b/models/request_header.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type RequestHeader struct { diff --git a/models/schedule.go b/models/schedule.go index 8dcbed8..72f4bac 100644 --- a/models/schedule.go +++ b/models/schedule.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type Schedule struct { diff --git a/models/schedule_log.go b/models/schedule_log.go index e5f356d..cc5f6d6 100644 --- a/models/schedule_log.go +++ b/models/schedule_log.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type ScheduleLog struct { diff --git a/models/triggered.go b/models/triggered.go index 8eb6745..cd099e3 100644 --- a/models/triggered.go +++ b/models/triggered.go @@ -1,6 +1,6 @@ package models -import "github.com/mstgnz/cronjob/config" +import "github.com/mstgnz/cronjob/pkg/config" type Triggered struct { ScheduleID int `json:"schedule_id"` diff --git a/models/user.go b/models/user.go index eca1ee4..69844f5 100644 --- a/models/user.go +++ b/models/user.go @@ -4,7 +4,8 @@ import ( "fmt" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/auth" + "github.com/mstgnz/cronjob/pkg/config" ) type User struct { @@ -109,7 +110,7 @@ func (m *User) Create(register *Register) error { return err } - hashPass := config.HashAndSalt(register.Password) + hashPass := auth.HashAndSalt(register.Password) err = stmt.QueryRow(register.Fullname, register.Email, hashPass, register.Phone).Scan(&m.ID, &m.Fullname, &m.Email, &m.Phone) if err != nil { return err @@ -266,7 +267,7 @@ func (m *User) PasswordUpdate(password string) error { } updateAt := time.Now().Format("2006-01-02 15:04:05") - hashPass := config.HashAndSalt(password) + hashPass := auth.HashAndSalt(password) result, err := stmt.Exec(hashPass, updateAt, m.ID) if err != nil { return err diff --git a/models/webhook.go b/models/webhook.go index a7c5087..f303da0 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/mstgnz/cronjob/config" + "github.com/mstgnz/cronjob/pkg/config" ) type Webhook struct { diff --git a/config/bcrypt.go b/pkg/auth/bcrypt.go similarity index 95% rename from config/bcrypt.go rename to pkg/auth/bcrypt.go index 1d31442..6635bbc 100644 --- a/config/bcrypt.go +++ b/pkg/auth/bcrypt.go @@ -1,4 +1,4 @@ -package config +package auth import ( "golang.org/x/crypto/bcrypt" diff --git a/config/jwt.go b/pkg/auth/jwt.go similarity index 90% rename from config/jwt.go rename to pkg/auth/jwt.go index 23394d1..a79d590 100644 --- a/config/jwt.go +++ b/pkg/auth/jwt.go @@ -1,4 +1,4 @@ -package config +package auth import ( "crypto/rand" @@ -8,6 +8,7 @@ import ( "time" "github.com/golang-jwt/jwt/v5" + "github.com/mstgnz/cronjob/pkg/config" ) var letterRunes = []rune("0987654321abcçdefgğhıijklmnoöpqrsştuüvwxyzABCÇDEFGĞHIİJKLMNOÖPQRSTUÜVWXYZ-_!?+&%=*") @@ -20,7 +21,7 @@ func GenerateToken(userId int) (string, error) { Issuer: strconv.Itoa(userId), } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - t, err := token.SignedString([]byte(App().SecretKey)) + t, err := token.SignedString([]byte(config.App().SecretKey)) if err != nil { return "", err } @@ -33,7 +34,7 @@ func ValidateToken(token string) (*jwt.Token, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method %v", t.Header["alg"]) } - return []byte(App().SecretKey), nil + return []byte(config.App().SecretKey), nil }) } diff --git a/pkg/cache.go b/pkg/cache/cache.go similarity index 99% rename from pkg/cache.go rename to pkg/cache/cache.go index 6bbed50..fa700fd 100644 --- a/pkg/cache.go +++ b/pkg/cache/cache.go @@ -1,4 +1,4 @@ -package pkg +package cache import ( "fmt" diff --git a/pkg/cache_test.go b/pkg/cache/cache_test.go similarity index 99% rename from pkg/cache_test.go rename to pkg/cache/cache_test.go index 0244be2..d0e7d40 100644 --- a/pkg/cache_test.go +++ b/pkg/cache/cache_test.go @@ -1,4 +1,4 @@ -package pkg +package cache import ( "testing" diff --git a/config/conf.go b/pkg/config/conf.go similarity index 73% rename from config/conf.go rename to pkg/config/conf.go index cf7cd09..d6324a0 100644 --- a/config/conf.go +++ b/pkg/config/conf.go @@ -11,45 +11,45 @@ import ( "sync" "github.com/go-playground/validator/v10" - "github.com/mstgnz/cronjob/pkg" + "github.com/mstgnz/cronjob/pkg/cache" + "github.com/mstgnz/cronjob/pkg/conn" + "github.com/mstgnz/cronjob/pkg/response" "github.com/robfig/cron/v3" ) -var ( - once sync.Once - mu sync.Mutex - instance *config -) - -// context key type type CKey string -type config struct { - DB *DB - ES *ES - Kraft *Kraft - Mail *pkg.Mail +type Manager struct { + DB *conn.DB + Mail *response.Mail + ES *conn.ES + Cache *cache.Cache + Kafka *conn.Kraft + Redis *conn.Redis Cron *cron.Cron - Cache *pkg.Cache - Log *Logger - Validador *validator.Validate + Validator *validator.Validate SecretKey string QUERY map[string]string Running int Shutting bool } -func App() *config { - once.Do(func() { - instance = &config{ - DB: &DB{}, - Cron: cron.New(), - Cache: pkg.NewCache(), - Log: &Logger{}, - Validador: validator.New(), +var ( + instance *Manager + mu sync.Mutex +) + +func App() *Manager { + if instance == nil { + instance = &Manager{ + DB: &conn.DB{}, + Cache: &cache.Cache{}, + Kafka: &conn.Kraft{}, + Redis: &conn.Redis{}, + Validator: &validator.Validate{}, // the secret key will change every time the application is restarted. SecretKey: "asdf1234", //RandomString(8), - Mail: &pkg.Mail{ + Mail: &response.Mail{ From: os.Getenv("MAIL_FROM"), Name: os.Getenv("MAIL_FROM_NAME"), Host: os.Getenv("MAIL_HOST"), @@ -61,18 +61,18 @@ func App() *config { // Connect to Postgres DB instance.DB.ConnectDatabase() // Connect to Kafka Kraft - if kraft, err := newKafkaClient(); err != nil { + if kraft, err := conn.NewKafkaClient(); err != nil { log.Println(err) } else { - instance.Kraft = kraft + instance.Kafka = kraft } // Connect to Elastic Search - if es, err := newESClient(); err != nil { + if es, err := conn.NewESClient(); err != nil { log.Println(err) } else { instance.ES = es } - }) + } return instance } diff --git a/config/db.go b/pkg/conn/db.go similarity index 98% rename from config/db.go rename to pkg/conn/db.go index fa6c14e..ad388c9 100644 --- a/config/db.go +++ b/pkg/conn/db.go @@ -1,4 +1,4 @@ -package config +package conn import ( "database/sql" diff --git a/config/es.go b/pkg/conn/es.go similarity index 93% rename from config/es.go rename to pkg/conn/es.go index c10e408..cdbe21d 100644 --- a/config/es.go +++ b/pkg/conn/es.go @@ -1,4 +1,4 @@ -package config +package conn import ( "crypto/tls" @@ -15,7 +15,7 @@ type ES struct { *elasticsearch.Client } -func newESClient() (*ES, error) { +func NewESClient() (*ES, error) { connStr := fmt.Sprintf("%s:%s", os.Getenv("ES_HOST"), os.Getenv("ES_PORT")) cfg := elasticsearch.Config{ Addresses: []string{connStr}, diff --git a/config/kraft.go b/pkg/conn/kraft.go similarity index 98% rename from config/kraft.go rename to pkg/conn/kraft.go index 51c8280..f999e62 100644 --- a/config/kraft.go +++ b/pkg/conn/kraft.go @@ -1,4 +1,4 @@ -package config +package conn import ( "crypto/tls" @@ -15,7 +15,7 @@ type Kraft struct { brokers []string } -func newKafkaClient() (*Kraft, error) { +func NewKafkaClient() (*Kraft, error) { connStr := fmt.Sprintf("%s:%s", os.Getenv("KRAFT_HOST"), os.Getenv("KRAFT_PORT")) client := &Kraft{ brokers: []string{connStr}, diff --git a/pkg/conn/redis.go b/pkg/conn/redis.go new file mode 100644 index 0000000..7cb90f1 --- /dev/null +++ b/pkg/conn/redis.go @@ -0,0 +1,44 @@ +package conn + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/redis/go-redis/v9" +) + +type Redis struct { + *redis.Client +} + +func (r *Redis) ConnectRedis() { + client := redis.NewClient(&redis.Options{ + Addr: fmt.Sprintf("%s:%s", os.Getenv("REDIS_URL"), os.Getenv("REDIS_PORT")), + Password: os.Getenv("REDIS_PASS"), + }) + r.Client = client + if client != nil { + log.Println("Redis Connected") + } else { + log.Println("Failed Redis Connection") + } +} + +func (r *Redis) CloseRedis() { + if err := r.Close(); err != nil { + log.Println(err.Error()) + } else { + log.Println("Redis Connection Closed") + } +} + +func (r *Redis) RedisWrite() error { + return r.Set(context.Background(), "example-key", "example-value", 0).Err() +} + +func (r *Redis) RedisRead() (string, error) { + value, err := r.Get(context.Background(), "example-key").Result() + return value, err +} diff --git a/config/load-sql.go b/pkg/load/load-sql.go similarity index 99% rename from config/load-sql.go rename to pkg/load/load-sql.go index af841d9..f6441f2 100644 --- a/config/load-sql.go +++ b/pkg/load/load-sql.go @@ -1,4 +1,4 @@ -package config +package load import ( "bufio" diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go new file mode 100644 index 0000000..d5a7727 --- /dev/null +++ b/pkg/logger/logger.go @@ -0,0 +1,42 @@ +package logger + +import ( + "log/slog" + "strings" + + "github.com/mstgnz/cronjob/pkg/config" +) + +func logToDB(level string, message string) { + stmt, err := config.App().DB.Prepare(config.App().QUERY["APP_LOG_INSERT"]) + if err == nil { + _, _ = stmt.Exec(level, message) + } + defer func() { + _ = stmt.Close() + }() +} + +func Info(message ...string) { + msg := strings.Join(message, ", ") + slog.Info(msg) + logToDB("INFO", msg) +} + +func Error(message ...string) { + msg := strings.Join(message, ", ") + slog.Error(msg) + logToDB("ERROR", msg) +} + +func Warn(message ...string) { + msg := strings.Join(message, ", ") + slog.Error(msg) + logToDB("WARNING", msg) +} + +func Debug(message ...string) { + msg := strings.Join(message, ", ") + slog.Debug(msg) + logToDB("DEBUG", msg) +} diff --git a/config/json.go b/pkg/response/json.go similarity index 99% rename from config/json.go rename to pkg/response/json.go index 34df7ff..8cbe185 100644 --- a/config/json.go +++ b/pkg/response/json.go @@ -1,4 +1,4 @@ -package config +package response import ( "encoding/json" diff --git a/pkg/mail.go b/pkg/response/mail.go similarity index 99% rename from pkg/mail.go rename to pkg/response/mail.go index 978cb49..0dd4537 100644 --- a/pkg/mail.go +++ b/pkg/response/mail.go @@ -1,4 +1,4 @@ -package pkg +package response import ( "crypto/tls" diff --git a/config/response.go b/pkg/response/response.go similarity index 96% rename from config/response.go rename to pkg/response/response.go index 414ea90..7e22d7a 100644 --- a/config/response.go +++ b/pkg/response/response.go @@ -1,4 +1,4 @@ -package config +package response type Response struct { Status bool `json:"status"` diff --git a/config/validate.go b/pkg/validate/validate.go similarity index 84% rename from config/validate.go rename to pkg/validate/validate.go index def2e1a..5db7c97 100644 --- a/config/validate.go +++ b/pkg/validate/validate.go @@ -1,4 +1,4 @@ -package config +package validate import ( "errors" @@ -6,10 +6,11 @@ import ( "reflect" "github.com/go-playground/validator/v10" + "github.com/mstgnz/cronjob/pkg/config" ) func Validate(structure any) error { - validate := App().Validador + validate := config.App().Validator var errStr string var errSlc []error // returns nil or ValidationErrors ( []FieldError ) @@ -42,8 +43,8 @@ func CustomValidate() { // The Go Playground Validator has a “cron” validation mechanism, but it does not work correctly. // So we will validate with “robfig/cron parser”. func CustomCronValidate() { - App().Validador.RegisterValidation("cron", func(fl validator.FieldLevel) bool { - _, err := App().Cron.AddFunc(fl.Field().String(), nil) + config.App().Validator.RegisterValidation("cron", func(fl validator.FieldLevel) bool { + _, err := config.App().Cron.AddFunc(fl.Field().String(), nil) return err == nil }) } @@ -52,7 +53,7 @@ func CustomCronValidate() { // In the case of slices, this tag checks if the slice itself exists, but does not check if the contents of the slice are empty. // We have written a special validation function to check if slices are empty. func CustomNoEmptyValidate() { - App().Validador.RegisterValidation("nonempty", func(fl validator.FieldLevel) bool { + config.App().Validator.RegisterValidation("nonempty", func(fl validator.FieldLevel) bool { field := fl.Field() // Ensure the field is a slice or array if field.Kind() != reflect.Slice && field.Kind() != reflect.Array { diff --git a/schedule/scheduler.go b/schedule/scheduler.go index d0cbd06..a381ef7 100644 --- a/schedule/scheduler.go +++ b/schedule/scheduler.go @@ -9,8 +9,9 @@ import ( "time" _ "time/tzdata" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/logger" "github.com/robfig/cron/v3" ) @@ -47,7 +48,7 @@ func AddSchedules(c *cron.Cron, schedules []*models.Schedule, scheduleMap map[in id, err := c.AddFunc(schedule.Timing, func() { defer func() { if r := recover(); r != nil { - config.App().Log.Warn("Recovered from panic in schedule", fmt.Sprintf("%v", r)) + logger.Warn("Recovered from panic in schedule", fmt.Sprintf("%v", r)) } }() @@ -61,7 +62,7 @@ func AddSchedules(c *cron.Cron, schedules []*models.Schedule, scheduleMap map[in } req, err := http.NewRequest(schedule.Request.Method, schedule.Request.Url, strings.NewReader(string(schedule.Request.Content))) if err != nil { - config.App().Log.Warn("Schedule Request Error", err.Error()) + logger.Warn("Schedule Request Error", err.Error()) return } @@ -77,7 +78,7 @@ func AddSchedules(c *cron.Cron, schedules []*models.Schedule, scheduleMap map[in if err == nil { break } - config.App().Log.Warn("Schedule Do Error, retrying", fmt.Sprintf("Attempt %d/%d: %v", retries+1, schedule.Retries, err.Error())) + logger.Warn("Schedule Do Error, retrying", fmt.Sprintf("Attempt %d/%d: %v", retries+1, schedule.Retries, err.Error())) time.Sleep(1 * time.Second) } scheduleUpdate(schedule, false) @@ -86,7 +87,7 @@ func AddSchedules(c *cron.Cron, schedules []*models.Schedule, scheduleMap map[in body, err := io.ReadAll(resp.Body) if err != nil { - config.App().Log.Warn("Schedule Body Error", err.Error()) + logger.Warn("Schedule Body Error", err.Error()) return } notification(schedule, body) @@ -101,7 +102,7 @@ func AddSchedules(c *cron.Cron, schedules []*models.Schedule, scheduleMap map[in webhooks(schedule) }) if err != nil { - config.App().Log.Warn("Schedule Error", err.Error()) + logger.Warn("Schedule Error", err.Error()) } else { scheduleMap[schedule.ID] = id } @@ -113,7 +114,7 @@ func scheduleUpdate(schedule *models.Schedule, running bool) { query := "UPDATE schedules SET running=$1 WHERE id=$2" err := schedule.Update(query, []any{running, schedule.ID}) if err != nil { - config.App().Log.Warn("Schedule Update Error", err.Error()) + logger.Warn("Schedule Update Error", err.Error()) } } @@ -125,7 +126,7 @@ func notification(schedule *models.Schedule, body []byte) { for _, mail := range schedule.Notification.NotifyEmails { err := config.App().Mail.SetSubject(schedule.Timing + " is running").SetContent(string(body)).SetTo(mail.Email).SendText() if err != nil { - config.App().Log.Warn("Schedule Mail Error", err.Error()) + logger.Warn("Schedule Mail Error", err.Error()) } } } @@ -150,13 +151,13 @@ func webhooks(schedule *models.Schedule) { req, err := http.NewRequest(webhook.Request.Method, webhook.Request.Url, strings.NewReader(string(webhook.Request.Content))) if err != nil { - config.App().Log.Warn("Schedule Webhook Error", err.Error()) + logger.Warn("Schedule Webhook Error", err.Error()) return } _, err = client.Do(req) if err != nil { - config.App().Log.Warn("Schedule Webhook Error", err.Error()) + logger.Warn("Schedule Webhook Error", err.Error()) return } }() diff --git a/services/group.go b/services/group.go index b97f50a..158366a 100644 --- a/services/group.go +++ b/services/group.go @@ -8,13 +8,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type GroupService struct{} -func (s *GroupService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *GroupService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { group := &models.Group{} // get auth user in context @@ -25,21 +27,21 @@ func (s *GroupService) ListService(w http.ResponseWriter, r *http.Request) (int, groups, err := group.Get(cUser.ID, id, uid) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"groups": groups}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"groups": groups}} } -func (s *GroupService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *GroupService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { group := &models.Group{} - if err := config.ReadJSON(w, r, group); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, group); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(group) + err := validate.Validate(group) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -49,29 +51,29 @@ func (s *GroupService) CreateService(w http.ResponseWriter, r *http.Request) (in exists, err := group.NameExists() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Group already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Group already exists"} } err = group.Create(config.App().DB.DB) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Group created", Data: map[string]any{"group": group}} + return http.StatusCreated, response.Response{Status: true, Message: "Group created", Data: map[string]any{"group": group}} } -func (s *GroupService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *GroupService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.GroupUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -81,10 +83,10 @@ func (s *GroupService) UpdateService(w http.ResponseWriter, r *http.Request) (in id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := groups.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Group not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Group not found"} } queryParts := []string{"UPDATE groups SET"} @@ -108,7 +110,7 @@ func (s *GroupService) UpdateService(w http.ResponseWriter, r *http.Request) (in } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -124,13 +126,13 @@ func (s *GroupService) UpdateService(w http.ResponseWriter, r *http.Request) (in err = groups.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *GroupService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *GroupService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -138,17 +140,17 @@ func (s *GroupService) DeleteService(w http.ResponseWriter, r *http.Request) (in id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := groups.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Group not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Group not found"} } err = groups.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } diff --git a/services/notification.go b/services/notification.go index 173ae1f..aa54507 100644 --- a/services/notification.go +++ b/services/notification.go @@ -8,13 +8,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type NotificationService struct{} -func (s *NotificationService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotificationService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { notification := &models.Notification{} // get auth user in context @@ -25,21 +27,21 @@ func (s *NotificationService) ListService(w http.ResponseWriter, r *http.Request notifications, err := notification.Get(cUser.ID, id, title) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"notifications": notifications}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"notifications": notifications}} } -func (s *NotificationService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotificationService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { notification := &models.Notification{} - if err := config.ReadJSON(w, r, notification); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, notification); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(notification) + err := validate.Validate(notification) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -49,29 +51,29 @@ func (s *NotificationService) CreateService(w http.ResponseWriter, r *http.Reque exists, err := notification.TitleExists() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Title already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Title already exists"} } err = notification.Create(config.App().DB.DB) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Notification created", Data: map[string]any{"notification": notification}} + return http.StatusCreated, response.Response{Status: true, Message: "Notification created", Data: map[string]any{"notification": notification}} } -func (s *NotificationService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotificationService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.NotificationUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -81,10 +83,10 @@ func (s *NotificationService) UpdateService(w http.ResponseWriter, r *http.Reque id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := notification.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } queryParts := []string{"UPDATE notifications SET"} @@ -118,7 +120,7 @@ func (s *NotificationService) UpdateService(w http.ResponseWriter, r *http.Reque } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -134,13 +136,13 @@ func (s *NotificationService) UpdateService(w http.ResponseWriter, r *http.Reque err = notification.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *NotificationService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotificationService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -148,30 +150,30 @@ func (s *NotificationService) DeleteService(w http.ResponseWriter, r *http.Reque id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := notification.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } err = notification.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } -func (s *NotificationService) BulkService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotificationService) BulkService(w http.ResponseWriter, r *http.Request) (int, response.Response) { bulk := &models.NotificationBulk{} - if err := config.ReadJSON(w, r, bulk); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, bulk); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(bulk) + err := validate.Validate(bulk) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -188,23 +190,23 @@ func (s *NotificationService) BulkService(w http.ResponseWriter, r *http.Request exists, err := notification.TitleExists() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Title already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Title already exists"} } tx, err := config.App().DB.Begin() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } err = notification.Create(tx) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } for _, email := range bulk.NotifyEmails { @@ -247,8 +249,8 @@ func (s *NotificationService) BulkService(w http.ResponseWriter, r *http.Request // Commit transaction if err := tx.Commit(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Notification created", Data: map[string]any{"notification": notification}} + return http.StatusCreated, response.Response{Status: true, Message: "Notification created", Data: map[string]any{"notification": notification}} } diff --git a/services/notifiy_email.go b/services/notifiy_email.go index f9b2a2a..cb887e3 100644 --- a/services/notifiy_email.go +++ b/services/notifiy_email.go @@ -8,13 +8,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type NotifyEmailService struct{} -func (s *NotifyEmailService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyEmailService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { notifyEmail := &models.NotifyEmail{} // get auth user in context @@ -25,21 +27,21 @@ func (s *NotifyEmailService) ListService(w http.ResponseWriter, r *http.Request) notifyEmails, err := notifyEmail.Get(cUser.ID, id, email) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"notify_emails": notifyEmails}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"notify_emails": notifyEmails}} } -func (s *NotifyEmailService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyEmailService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { notifyEmail := &models.NotifyEmail{} - if err := config.ReadJSON(w, r, notifyEmail); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, notifyEmail); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(notifyEmail) + err := validate.Validate(notifyEmail) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -48,37 +50,37 @@ func (s *NotifyEmailService) CreateService(w http.ResponseWriter, r *http.Reques notification := &models.Notification{} exists, err := notification.IDExists(notifyEmail.NotificationID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } exists, err = notifyEmail.EmailExists(config.App().DB.DB, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Email already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Email already exists"} } err = notifyEmail.Create(config.App().DB.DB) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Notify email created", Data: map[string]any{"notify_email": notifyEmail}} + return http.StatusCreated, response.Response{Status: true, Message: "Notify email created", Data: map[string]any{"notify_email": notifyEmail}} } -func (s *NotifyEmailService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyEmailService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.NotifyEmailUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -88,10 +90,10 @@ func (s *NotifyEmailService) UpdateService(w http.ResponseWriter, r *http.Reques id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := notifyEmail.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notify email not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notify email not found"} } queryParts := []string{"UPDATE notify_emails SET"} @@ -115,7 +117,7 @@ func (s *NotifyEmailService) UpdateService(w http.ResponseWriter, r *http.Reques } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -131,13 +133,13 @@ func (s *NotifyEmailService) UpdateService(w http.ResponseWriter, r *http.Reques err = notifyEmail.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *NotifyEmailService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyEmailService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -145,17 +147,17 @@ func (s *NotifyEmailService) DeleteService(w http.ResponseWriter, r *http.Reques id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := notifyEmail.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notify email not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notify email not found"} } err = notifyEmail.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } diff --git a/services/notifiy_message.go b/services/notifiy_message.go index b2046d8..f8a412f 100644 --- a/services/notifiy_message.go +++ b/services/notifiy_message.go @@ -8,13 +8,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type NotifyMessageService struct{} -func (s *NotifyMessageService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyMessageService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { notifyMessage := &models.NotifyMessage{} // get auth user in context @@ -25,21 +27,21 @@ func (s *NotifyMessageService) ListService(w http.ResponseWriter, r *http.Reques notifyMessages, err := notifyMessage.Get(cUser.ID, id, phone) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"notify_messages": notifyMessages}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"notify_messages": notifyMessages}} } -func (s *NotifyMessageService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyMessageService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { notifyMessage := &models.NotifyMessage{} - if err := config.ReadJSON(w, r, notifyMessage); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, notifyMessage); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(notifyMessage) + err := validate.Validate(notifyMessage) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -48,37 +50,37 @@ func (s *NotifyMessageService) CreateService(w http.ResponseWriter, r *http.Requ notification := &models.Notification{} exists, err := notification.IDExists(notifyMessage.NotificationID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } exists, err = notifyMessage.PhoneExists(config.App().DB.DB, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Phone already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Phone already exists"} } err = notifyMessage.Create(config.App().DB.DB) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Notify message created", Data: map[string]any{"notify_message": notifyMessage}} + return http.StatusCreated, response.Response{Status: true, Message: "Notify message created", Data: map[string]any{"notify_message": notifyMessage}} } -func (s *NotifyMessageService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyMessageService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.NotifyMessageUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -88,10 +90,10 @@ func (s *NotifyMessageService) UpdateService(w http.ResponseWriter, r *http.Requ id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := notifyMessage.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notify message not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notify message not found"} } queryParts := []string{"UPDATE notify_messages SET"} @@ -115,7 +117,7 @@ func (s *NotifyMessageService) UpdateService(w http.ResponseWriter, r *http.Requ } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -131,13 +133,13 @@ func (s *NotifyMessageService) UpdateService(w http.ResponseWriter, r *http.Requ err = notifyMessage.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *NotifyMessageService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *NotifyMessageService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -145,17 +147,17 @@ func (s *NotifyMessageService) DeleteService(w http.ResponseWriter, r *http.Requ id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := notifyMessage.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notify message not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notify message not found"} } err = notifyMessage.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } diff --git a/services/render.go b/services/render.go index 60e8f7f..4d1fefb 100644 --- a/services/render.go +++ b/services/render.go @@ -6,8 +6,8 @@ import ( "net/http" "path" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" ) func Render(w http.ResponseWriter, r *http.Request, page string, data map[string]any, partials ...string) error { diff --git a/services/request.go b/services/request.go index e25e779..f39b7e4 100644 --- a/services/request.go +++ b/services/request.go @@ -9,13 +9,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type RequestService struct{} -func (h *RequestService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *RequestService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { request := &models.Request{} // get auth user in context @@ -26,21 +28,21 @@ func (h *RequestService) ListService(w http.ResponseWriter, r *http.Request) (in requests, err := request.Get(cUser.ID, id, url) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"requests": requests}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"requests": requests}} } -func (h *RequestService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *RequestService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { request := &models.Request{} - if err := config.ReadJSON(w, r, request); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, request); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(request) + err := validate.Validate(request) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -50,29 +52,29 @@ func (h *RequestService) CreateService(w http.ResponseWriter, r *http.Request) ( exists, err := request.UrlExists() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Url already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Url already exists"} } err = request.Create(config.App().DB.DB) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Request created", Data: map[string]any{"request": request}} + return http.StatusCreated, response.Response{Status: true, Message: "Request created", Data: map[string]any{"request": request}} } -func (h *RequestService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *RequestService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.RequestUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -82,10 +84,10 @@ func (h *RequestService) UpdateService(w http.ResponseWriter, r *http.Request) ( id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := request.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } queryParts := []string{"UPDATE requests SET"} @@ -114,7 +116,7 @@ func (h *RequestService) UpdateService(w http.ResponseWriter, r *http.Request) ( } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -130,13 +132,13 @@ func (h *RequestService) UpdateService(w http.ResponseWriter, r *http.Request) ( err = request.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (h *RequestService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *RequestService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -144,30 +146,30 @@ func (h *RequestService) DeleteService(w http.ResponseWriter, r *http.Request) ( id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := request.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } err = request.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } -func (s *RequestService) RequestBulkService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *RequestService) RequestBulkService(w http.ResponseWriter, r *http.Request) (int, response.Response) { bulk := &models.RequestBulk{} - if err := config.ReadJSON(w, r, bulk); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, bulk); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(bulk) + err := validate.Validate(bulk) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -183,23 +185,23 @@ func (s *RequestService) RequestBulkService(w http.ResponseWriter, r *http.Reque exists, err := request.UrlExists() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Url already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Url already exists"} } tx, err := config.App().DB.Begin() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } err = request.Create(tx) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } for _, header := range bulk.RequestHeaders { @@ -224,8 +226,8 @@ func (s *RequestService) RequestBulkService(w http.ResponseWriter, r *http.Reque // Commit transaction if err := tx.Commit(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "test", Data: map[string]any{"request": request}} + return http.StatusCreated, response.Response{Status: true, Message: "test", Data: map[string]any{"request": request}} } diff --git a/services/request_header.go b/services/request_header.go index cf9748e..97097e5 100644 --- a/services/request_header.go +++ b/services/request_header.go @@ -8,13 +8,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type RequestHeaderService struct{} -func (s *RequestHeaderService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *RequestHeaderService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { requestHeader := &models.RequestHeader{} // get auth user in context @@ -26,21 +28,21 @@ func (s *RequestHeaderService) ListService(w http.ResponseWriter, r *http.Reques requestHeaders, err := requestHeader.Get(cUser.ID, id, requestID, key) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"request_headers": requestHeaders}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"request_headers": requestHeaders}} } -func (s *RequestHeaderService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *RequestHeaderService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { requestHeader := &models.RequestHeader{} - if err := config.ReadJSON(w, r, requestHeader); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, requestHeader); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(requestHeader) + err := validate.Validate(requestHeader) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -50,38 +52,38 @@ func (s *RequestHeaderService) CreateService(w http.ResponseWriter, r *http.Requ request := &models.Request{} exists, err := request.IDExists(requestHeader.RequestID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } // check header key exists, err = requestHeader.HeaderExists(config.App().DB.DB, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Header already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Header already exists"} } err = requestHeader.Create(config.App().DB.DB) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Request Header created", Data: map[string]any{"request_header": requestHeader}} + return http.StatusCreated, response.Response{Status: true, Message: "Request Header created", Data: map[string]any{"request_header": requestHeader}} } -func (s *RequestHeaderService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *RequestHeaderService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.RequestHeaderUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -91,10 +93,10 @@ func (s *RequestHeaderService) UpdateService(w http.ResponseWriter, r *http.Requ id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := requestHeader.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request Header not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request Header not found"} } queryParts := []string{"UPDATE request_headers SET"} @@ -123,7 +125,7 @@ func (s *RequestHeaderService) UpdateService(w http.ResponseWriter, r *http.Requ } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -139,13 +141,13 @@ func (s *RequestHeaderService) UpdateService(w http.ResponseWriter, r *http.Requ err = requestHeader.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *RequestHeaderService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *RequestHeaderService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -153,17 +155,17 @@ func (s *RequestHeaderService) DeleteService(w http.ResponseWriter, r *http.Requ id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := requestHeader.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request Header not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request Header not found"} } err = requestHeader.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } diff --git a/services/schedule.go b/services/schedule.go index 2e19ca3..bcc7bbd 100644 --- a/services/schedule.go +++ b/services/schedule.go @@ -9,14 +9,16 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type ScheduleService struct { } -func (s *ScheduleService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *ScheduleService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { schedule := &models.Schedule{} // get auth user in context @@ -30,21 +32,21 @@ func (s *ScheduleService) ListService(w http.ResponseWriter, r *http.Request) (i schedules, err := schedule.Get(id, cUser.ID, group_id, request_id, notification_id, timing) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"schedules": schedules}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"schedules": schedules}} } -func (s *ScheduleService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *ScheduleService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { schedule := &models.Schedule{} - if err := config.ReadJSON(w, r, schedule); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, schedule); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(schedule) + err := validate.Validate(schedule) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -56,58 +58,58 @@ func (s *ScheduleService) CreateService(w http.ResponseWriter, r *http.Request) groups := &models.Group{} exists, err := groups.IDExists(schedule.GroupID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Group not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Group not found"} } // request check request := &models.Request{} exists, err = request.IDExists(schedule.RequestID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } // notification check notification := &models.Notification{} exists, err = notification.IDExists(schedule.NotificationID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } // timinng check with request exists, err = schedule.TimingExists(cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusCreated, config.Response{Status: false, Message: "Timing already exists"} + return http.StatusCreated, response.Response{Status: false, Message: "Timing already exists"} } err = schedule.Create(config.App().DB.DB) if err != nil { - return http.StatusCreated, config.Response{Status: false, Message: err.Error()} + return http.StatusCreated, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Schedule created", Data: map[string]any{"schedule": schedule}} + return http.StatusCreated, response.Response{Status: true, Message: "Schedule created", Data: map[string]any{"schedule": schedule}} } -func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.ScheduleUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -117,10 +119,10 @@ func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := schedule.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Schedule not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Schedule not found"} } queryParts := []string{"UPDATE schedules SET"} @@ -132,10 +134,10 @@ func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) group := &models.Group{} exists, err := group.IDExists(schedule.GroupID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Group not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Group not found"} } // add query queryParts = append(queryParts, fmt.Sprintf("group_id=$%d,", paramCount)) @@ -147,10 +149,10 @@ func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) request := &models.Request{} exists, err = request.IDExists(schedule.RequestID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } // add query queryParts = append(queryParts, fmt.Sprintf("request_id=$%d,", paramCount)) @@ -162,10 +164,10 @@ func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) notification := &models.Notification{} exists, err = notification.IDExists(schedule.NotificationID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } // add query queryParts = append(queryParts, fmt.Sprintf("notification_id=$%d,", paramCount)) @@ -194,7 +196,7 @@ func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -210,13 +212,13 @@ func (s *ScheduleService) UpdateService(w http.ResponseWriter, r *http.Request) err = schedule.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *ScheduleService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *ScheduleService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -224,22 +226,22 @@ func (s *ScheduleService) DeleteService(w http.ResponseWriter, r *http.Request) id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := schedule.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Schedule not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Schedule not found"} } err = schedule.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } -func (s *ScheduleService) LogListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *ScheduleService) LogListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { scheduleLog := &models.ScheduleLog{} // get auth user in context @@ -248,35 +250,35 @@ func (s *ScheduleService) LogListService(w http.ResponseWriter, r *http.Request) id, _ := strconv.Atoi(r.URL.Query().Get("id")) schedule_id, _ := strconv.Atoi(r.URL.Query().Get("schedule_id")) if schedule_id == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "schedule_id param required"} + return http.StatusBadRequest, response.Response{Status: false, Message: "schedule_id param required"} } schedule := &models.Schedule{} exists, err := schedule.IDExists(schedule_id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Schedule not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Schedule not found"} } scheduleLogs, err := scheduleLog.Get(id, schedule_id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"schedule_logs": scheduleLogs}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"schedule_logs": scheduleLogs}} } -func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (int, response.Response) { bulk := &models.ScheduleBulk{} - if err := config.ReadJSON(w, r, bulk); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, bulk); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(bulk) + err := validate.Validate(bulk) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -295,7 +297,7 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i tx, err := config.App().DB.Begin() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } // group check @@ -305,14 +307,14 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i if schedule.GroupID > 0 { exists, err := group.IDExists(schedule.GroupID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Group not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Group not found"} } } else { if bulk.Group == nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Group or Group ID required"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Group or Group ID required"} } group.Name = bulk.Group.Name @@ -321,9 +323,9 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i err = group.Create(tx) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } schedule.GroupID = group.ID } @@ -336,27 +338,27 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i exists, err := request.IDExists(schedule.RequestID, cUser.ID) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } } else { /* requestService := RequestService{} bodyBytes, err := json.Marshal(bulk.Request) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError,response.Response{Status: false, Message: err.Error()} } r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) requestService.RequestBulkService(w, r) */ if bulk.Request == nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Request or Request ID required"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Request or Request ID required"} } request.Url = bulk.Request.Url @@ -367,22 +369,22 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i exists, err := request.UrlExists() if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusBadRequest, config.Response{Status: false, Message: "Url already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Url already exists"} } err = request.Create(tx) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } for _, header := range bulk.Request.RequestHeaders { requestHeader := &models.RequestHeader{ @@ -415,19 +417,19 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i exists, err := notification.IDExists(schedule.NotificationID, cUser.ID) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusNotFound, config.Response{Status: false, Message: "Notification not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Notification not found"} } } else { if bulk.Notification == nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Notification or Notification ID required"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Notification or Notification ID required"} } notification.Title = bulk.Notification.Title @@ -439,22 +441,22 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i exists, err := notification.TitleExists() if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusBadRequest, config.Response{Status: false, Message: "Title already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Title already exists"} } err = notification.Create(tx) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } for _, email := range bulk.Notification.NotifyEmails { notifyEmail := &models.NotifyEmail{ @@ -499,15 +501,15 @@ func (s *ScheduleService) BulkService(w http.ResponseWriter, r *http.Request) (i err = schedule.Create(tx) if err != nil { if err := tx.Rollback(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } // Commit transaction if err := tx.Commit(); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Schedule created", Data: map[string]any{"schedule": schedule}} + return http.StatusCreated, response.Response{Status: true, Message: "Schedule created", Data: map[string]any{"schedule": schedule}} } diff --git a/services/user.go b/services/user.go index 03797ed..b887545 100644 --- a/services/user.go +++ b/services/user.go @@ -8,36 +8,39 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/auth" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type UserService struct{} -func (s *UserService) LoginService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) LoginService(w http.ResponseWriter, r *http.Request) (int, response.Response) { login := &models.Login{} - if err := config.ReadJSON(w, r, login); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, login); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(login) + err := validate.Validate(login) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } user := &models.User{} err = user.GetWithMail(login.Email) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - if !config.ComparePassword(user.Password, login.Password) { - return http.StatusBadRequest, config.Response{Status: false, Message: "Invalid credentials"} + if !auth.ComparePassword(user.Password, login.Password) { + return http.StatusBadRequest, response.Response{Status: false, Message: "Invalid credentials"} } - token, err := config.GenerateToken(user.ID) + token, err := auth.GenerateToken(user.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: "Failed to generate token"} + return http.StatusInternalServerError, response.Response{Status: false, Message: "Failed to generate token"} } // update last_login @@ -46,66 +49,66 @@ func (s *UserService) LoginService(w http.ResponseWriter, r *http.Request) (int, data := make(map[string]any) data["token"] = token data["user"] = user - return http.StatusOK, config.Response{Status: true, Message: "Login successful", Data: data} + return http.StatusOK, response.Response{Status: true, Message: "Login successful", Data: data} } -func (s *UserService) RegisterService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) RegisterService(w http.ResponseWriter, r *http.Request) (int, response.Response) { register := &models.Register{} - if err := config.ReadJSON(w, r, register); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, register); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(register) + err := validate.Validate(register) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } user := &models.User{} exists, err := user.Exists(register.Email) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Email already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Email already exists"} } err = user.Create(register) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - token, err := config.GenerateToken(user.ID) + token, err := auth.GenerateToken(user.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: "Failed to generate token"} + return http.StatusInternalServerError, response.Response{Status: false, Message: "Failed to generate token"} } data := make(map[string]any) data["token"] = token data["user"] = user - return http.StatusCreated, config.Response{Status: true, Message: "User created", Data: data} + return http.StatusCreated, response.Response{Status: true, Message: "User created", Data: data} } -func (s *UserService) ProfileService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) ProfileService(w http.ResponseWriter, r *http.Request) (int, response.Response) { user := r.Context().Value(config.CKey("user")) - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"user": user}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"user": user}} } -func (s *UserService) Users(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) Users(w http.ResponseWriter, r *http.Request) (int, response.Response) { user := &models.User{} count := user.Count() users := user.Get(0, 20, "") - return http.StatusOK, config.Response{Status: count > 0, Message: "Success", Data: map[string]any{"count": count, "users": users}} + return http.StatusOK, response.Response{Status: count > 0, Message: "Success", Data: map[string]any{"count": count, "users": users}} } -func (s *UserService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.ProfileUpdate{} - if err := config.ReadJSON(w, r, updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } user := &models.User{} @@ -130,15 +133,15 @@ func (s *UserService) UpdateService(w http.ResponseWriter, r *http.Request) (int if updateData.Email != "" { // check email if not same email if err := user.GetWithId(user.ID); err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if user.Email != updateData.Email { exists, err := user.Exists(updateData.Email) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusBadRequest, config.Response{Status: false, Message: "Email already exists"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Email already exists"} } } queryParts = append(queryParts, fmt.Sprintf("email=$%d,", paramCount)) @@ -152,7 +155,7 @@ func (s *UserService) UpdateService(w http.ResponseWriter, r *http.Request) (int } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -172,25 +175,25 @@ func (s *UserService) UpdateService(w http.ResponseWriter, r *http.Request) (int err = user.ProfileUpdate(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *UserService) PassUpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) PassUpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.PasswordUpdate{} - if err := config.ReadJSON(w, r, updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } if updateData.Password != updateData.RePassword { - return http.StatusBadRequest, config.Response{Status: false, Message: "Passwords do not match"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Passwords do not match"} } // get auth user in context @@ -207,40 +210,40 @@ func (s *UserService) PassUpdateService(w http.ResponseWriter, r *http.Request) err = user.PasswordUpdate(updateData.Password) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (s *UserService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (s *UserService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) if !cUser.IsAdmin { - return http.StatusForbidden, config.Response{Status: false, Message: "You're not a admin!"} + return http.StatusForbidden, response.Response{Status: false, Message: "You're not a admin!"} } user := &models.User{} id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := user.IDExists(id) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "User not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "User not found"} } err = user.Delete(id) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if user.ID == cUser.ID { - return http.StatusBadRequest, config.Response{Status: false, Message: "You can't erase yourself!"} + return http.StatusBadRequest, response.Response{Status: false, Message: "You can't erase yourself!"} } if user.IsAdmin { - return http.StatusBadRequest, config.Response{Status: false, Message: "Admin cannot delete admin!"} + return http.StatusBadRequest, response.Response{Status: false, Message: "Admin cannot delete admin!"} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } diff --git a/services/webhook.go b/services/webhook.go index 5ac8ca6..c757bc5 100644 --- a/services/webhook.go +++ b/services/webhook.go @@ -8,13 +8,15 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/mstgnz/cronjob/config" "github.com/mstgnz/cronjob/models" + "github.com/mstgnz/cronjob/pkg/config" + "github.com/mstgnz/cronjob/pkg/response" + "github.com/mstgnz/cronjob/pkg/validate" ) type WebhookService struct{} -func (h *WebhookService) ListService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *WebhookService) ListService(w http.ResponseWriter, r *http.Request) (int, response.Response) { webhook := &models.Webhook{} // get auth user in context @@ -25,26 +27,26 @@ func (h *WebhookService) ListService(w http.ResponseWriter, r *http.Request) (in request_id, _ := strconv.Atoi(r.URL.Query().Get("request_id")) if id == 0 && schedule_id == 0 && request_id == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "id, schedule_id or request_id param required"} + return http.StatusBadRequest, response.Response{Status: false, Message: "id, schedule_id or request_id param required"} } webhooks, err := webhook.Get(id, schedule_id, request_id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"webhooks": webhooks}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"webhooks": webhooks}} } -func (h *WebhookService) CreateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *WebhookService) CreateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { webhook := &models.Webhook{} - if err := config.ReadJSON(w, r, webhook); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, webhook); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(webhook) + err := validate.Validate(webhook) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -54,48 +56,48 @@ func (h *WebhookService) CreateService(w http.ResponseWriter, r *http.Request) ( schedule := &models.Schedule{} exists, err := schedule.IDExists(webhook.ScheduleID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Schedule not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Schedule not found"} } // check request_id request := &models.Request{} exists, err = request.IDExists(webhook.RequestID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Request not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Request not found"} } // check schedule_id and request_id exists, err = webhook.UniqExists(webhook.ScheduleID, webhook.RequestID, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Webhook already exists"} + return http.StatusNotFound, response.Response{Status: false, Message: "Webhook already exists"} } err = webhook.Create() if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusCreated, config.Response{Status: true, Message: "Webhook created", Data: map[string]any{"webhook": webhook}} + return http.StatusCreated, response.Response{Status: true, Message: "Webhook created", Data: map[string]any{"webhook": webhook}} } -func (h *WebhookService) UpdateService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *WebhookService) UpdateService(w http.ResponseWriter, r *http.Request) (int, response.Response) { updateData := &models.WebhookUpdate{} - if err := config.ReadJSON(w, r, &updateData); err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: err.Error()} + if err := response.ReadJSON(w, r, &updateData); err != nil { + return http.StatusBadRequest, response.Response{Status: false, Message: err.Error()} } - err := config.Validate(updateData) + err := validate.Validate(updateData) if err != nil { - return http.StatusBadRequest, config.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} + return http.StatusBadRequest, response.Response{Status: false, Message: "Content validation invalid", Data: map[string]any{"error": err.Error()}} } // get auth user in context @@ -105,10 +107,10 @@ func (h *WebhookService) UpdateService(w http.ResponseWriter, r *http.Request) ( id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := webhook.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Webhook not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Webhook not found"} } queryParts := []string{"UPDATE webhooks SET"} @@ -132,7 +134,7 @@ func (h *WebhookService) UpdateService(w http.ResponseWriter, r *http.Request) ( } if len(params) == 0 { - return http.StatusBadRequest, config.Response{Status: false, Message: "No fields to update"} + return http.StatusBadRequest, response.Response{Status: false, Message: "No fields to update"} } // update at @@ -148,13 +150,13 @@ func (h *WebhookService) UpdateService(w http.ResponseWriter, r *http.Request) ( err = webhook.Update(query, params) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} + return http.StatusOK, response.Response{Status: true, Message: "Success", Data: map[string]any{"update": updateData}} } -func (h *WebhookService) DeleteService(w http.ResponseWriter, r *http.Request) (int, config.Response) { +func (h *WebhookService) DeleteService(w http.ResponseWriter, r *http.Request) (int, response.Response) { // get auth user in context cUser, _ := r.Context().Value(config.CKey("user")).(*models.User) @@ -162,17 +164,17 @@ func (h *WebhookService) DeleteService(w http.ResponseWriter, r *http.Request) ( id, _ := strconv.Atoi(chi.URLParam(r, "id")) exists, err := webhook.IDExists(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } if !exists { - return http.StatusNotFound, config.Response{Status: false, Message: "Webhook not found"} + return http.StatusNotFound, response.Response{Status: false, Message: "Webhook not found"} } err = webhook.Delete(id, cUser.ID) if err != nil { - return http.StatusInternalServerError, config.Response{Status: false, Message: err.Error()} + return http.StatusInternalServerError, response.Response{Status: false, Message: err.Error()} } - return http.StatusOK, config.Response{Status: true, Message: "Soft delte success"} + return http.StatusOK, response.Response{Status: true, Message: "Soft delte success"} } diff --git a/test.html b/test.html deleted file mode 100644 index e69de29..0000000