Skip to content

Commit

Permalink
Refactor code hexagonal
Browse files Browse the repository at this point in the history
  • Loading branch information
voltgizerz committed Jul 12, 2024
1 parent 79d6414 commit e2d8016
Show file tree
Hide file tree
Showing 30 changed files with 67 additions and 64 deletions.
2 changes: 1 addition & 1 deletion .github/labeler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pkg:
- pkg/**/*

mocks:
- internal/app/mocks/*
- internal/mocks/*

changelog:
- CHANGELOG.md
Expand Down
10 changes: 5 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ decrypt-gpg:
@gpg -d .env.gpg

mock-gen:
@mockgen -source=./internal/app/ports/auth_ports.go -destination=./internal/app/mocks/mocks_auth.go -package=mocks
@mockgen -source=./internal/app/ports/user_ports.go -destination=./internal/app/mocks/mocks_user.go -package=mocks
@mockgen -source=./internal/app/ports/auth_ports.go -destination=./internal/mocks/mocks_auth.go -package=mocks
@mockgen -source=./internal/app/ports/user_ports.go -destination=./internal/mocks/mocks_user.go -package=mocks

changelog-gen:
@auto-changelog

# Target to apply migrations
up:
@goose -dir=./database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" up
@goose -dir=./internal/database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" up

# Target to reset migrations (if needed)
down:
@goose -dir=./database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" reset
@goose -dir=./internal/database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" reset

status:
@goose -dir=./database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" status
@goose -dir=./internal/database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" status
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import (
"syscall"

"github.com/voltgizerz/POS-restaurant/config"
"github.com/voltgizerz/POS-restaurant/database"
"github.com/voltgizerz/POS-restaurant/internal/app/api"
"github.com/voltgizerz/POS-restaurant/internal/app/api/handler"
"github.com/voltgizerz/POS-restaurant/internal/app/api/middleware"
"github.com/voltgizerz/POS-restaurant/internal/app/auth"
"github.com/voltgizerz/POS-restaurant/internal/app/interactor"
"github.com/voltgizerz/POS-restaurant/internal/app/repository"
"github.com/voltgizerz/POS-restaurant/internal/app/service"
"github.com/voltgizerz/POS-restaurant/internal/database"
"github.com/voltgizerz/POS-restaurant/pkg/jeager"
"github.com/voltgizerz/POS-restaurant/pkg/logger"
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package handler
package common

import (
"github.com/gofiber/fiber/v3"
"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/constants"
)

type (
errorResponse struct {
ErrorResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}

successResponse struct {
SuccessResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Data interface{} `json:"data"`
Expand All @@ -22,7 +22,7 @@ type (

// SendErrorResp generates and sends error response
func SendErrorResp(c fiber.Ctx, statusCode int, errorMessage string) error {
response := errorResponse{
response := ErrorResponse{
Success: false,
Message: errorMessage,
RequestID: c.Locals(constants.CTXKeyRequestID).(string),
Expand All @@ -33,7 +33,7 @@ func SendErrorResp(c fiber.Ctx, statusCode int, errorMessage string) error {

// SendSuccessResp generates and sends success response with dynamic data
func SendSuccessResp(c fiber.Ctx, statusCode int, message string, data interface{}) error {
response := successResponse{
response := SuccessResponse{
Success: true,
Message: message,
Data: data,
Expand Down
23 changes: 12 additions & 11 deletions internal/app/api/handler/auth_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
"github.com/gofiber/fiber/v3"
"github.com/opentracing/opentracing-go"

"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/app/api/common"
"github.com/voltgizerz/POS-restaurant/internal/app/entity"
"github.com/voltgizerz/POS-restaurant/internal/app/interactor"
"github.com/voltgizerz/POS-restaurant/internal/app/ports"
"github.com/voltgizerz/POS-restaurant/internal/constants"
"github.com/voltgizerz/POS-restaurant/internal/utils"
)

Expand All @@ -32,26 +33,26 @@ func (h *AuthHandler) Login(c fiber.Ctx) error {

err := c.Bind().Body(req)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgInvalidUsernameAndPassword)
return common.SendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgInvalidUsernameAndPassword)
}

err = validator.New().StructCtx(ctx, req)
if err != nil {
err = utils.GetFirstValidatorError(err)

return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

dataLogin, err := h.authService.Login(ctx, req.Username, req.Password)
if err != nil {
if err == sql.ErrNoRows {
return SendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgUsernameNotFound)
return common.SendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgUsernameNotFound)
}

return SendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgInvalidUsernameOrPassword)
return common.SendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgInvalidUsernameOrPassword)
}

return SendSuccessResp(c, fiber.StatusOK, "Success", dataLogin)
return common.SendSuccessResp(c, fiber.StatusOK, "Success", dataLogin)
}

func (h *AuthHandler) Register(c fiber.Ctx) error {
Expand All @@ -62,18 +63,18 @@ func (h *AuthHandler) Register(c fiber.Ctx) error {

err := c.Bind().Body(req)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, "Invalid request body.")
return common.SendErrorResp(c, fiber.StatusBadRequest, "Invalid request body.")
}

err = validator.New().StructCtx(ctx, req)
if err != nil {
err = utils.GetFirstValidatorError(err)

return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

if req.Password != req.ConfirmPassword {
return SendErrorResp(c, fiber.StatusBadRequest, "Password mismatch")
return common.SendErrorResp(c, fiber.StatusBadRequest, "Password mismatch")
}

userData := &entity.User{
Expand All @@ -85,12 +86,12 @@ func (h *AuthHandler) Register(c fiber.Ctx) error {

result, err := h.authService.Register(ctx, *userData)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

res := map[string]int64{
"user_id": result,
}

return SendSuccessResp(c, fiber.StatusCreated, "Account created succesfully.", res)
return common.SendSuccessResp(c, fiber.StatusCreated, "Account created succesfully.", res)
}
2 changes: 1 addition & 1 deletion internal/app/api/handler/auth_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import (
"github.com/bytedance/sonic"
"github.com/gofiber/fiber/v3"
"github.com/valyala/fasthttp"
"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/app/entity"
"github.com/voltgizerz/POS-restaurant/internal/app/interactor"
"github.com/voltgizerz/POS-restaurant/internal/constants"
"go.uber.org/mock/gomock"
)

Expand Down
2 changes: 1 addition & 1 deletion internal/app/api/handler/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

"go.uber.org/mock/gomock"

"github.com/voltgizerz/POS-restaurant/internal/app/mocks"
"github.com/voltgizerz/POS-restaurant/internal/mocks"
"github.com/voltgizerz/POS-restaurant/pkg/logger"
)

Expand Down
39 changes: 20 additions & 19 deletions internal/app/api/handler/menu_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import (

"github.com/gofiber/fiber/v3"
"github.com/opentracing/opentracing-go"
"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/app/api/common"
"github.com/voltgizerz/POS-restaurant/internal/app/entity"
"github.com/voltgizerz/POS-restaurant/internal/app/interactor"
"github.com/voltgizerz/POS-restaurant/internal/app/ports"
"github.com/voltgizerz/POS-restaurant/internal/constants"
)

type MenuHandler struct {
Expand All @@ -30,12 +31,12 @@ func (h *MenuHandler) AddMenu(c fiber.Ctx) error {

err := c.Bind().Body(req)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, "Error data menu")
return common.SendErrorResp(c, fiber.StatusBadRequest, "Error data menu")
}

priceConvert, err := strconv.ParseFloat(req.Price, 64)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

menuData := &entity.Menu{
Expand All @@ -48,14 +49,14 @@ func (h *MenuHandler) AddMenu(c fiber.Ctx) error {

result, err := h.menuService.RegisterMenu(ctx, *menuData)
if err != nil {
return SendErrorResp(c, fiber.StatusUnauthorized, err.Error())
return common.SendErrorResp(c, fiber.StatusUnauthorized, err.Error())
}

responseMsg := map[string]int64{
"menu_id": result,
}

return SendSuccessResp(c, fiber.StatusOK, "Success", responseMsg)
return common.SendSuccessResp(c, fiber.StatusOK, "Success", responseMsg)
}

func (h *MenuHandler) GetMenuByUserID(c fiber.Ctx) error {
Expand All @@ -65,15 +66,15 @@ func (h *MenuHandler) GetMenuByUserID(c fiber.Ctx) error {
userID := c.Params("user_id")
convertUserIDtoInt, err := strconv.Atoi(userID)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

result, err := h.menuService.GetMenu(ctx, int64(convertUserIDtoInt))
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgMenuNotFound)
return common.SendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgMenuNotFound)
}

return SendSuccessResp(c, fiber.StatusOK, "Success", result)
return common.SendSuccessResp(c, fiber.StatusOK, "Success", result)
}

func (h *MenuHandler) UpdateMenuByMenuID(c fiber.Ctx) error {
Expand All @@ -83,18 +84,18 @@ func (h *MenuHandler) UpdateMenuByMenuID(c fiber.Ctx) error {
req := &updateMenuRequest{}
err := c.Bind().Body(req)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, "Invalid request body.")
return common.SendErrorResp(c, fiber.StatusBadRequest, "Invalid request body.")
}

menuID := c.Params("menu_id")
convertMenuIDtoInt, err := strconv.Atoi(menuID)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

priceConvert, err := strconv.ParseFloat(req.Price, 64)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

menuData := entity.Menu{
Expand All @@ -108,10 +109,10 @@ func (h *MenuHandler) UpdateMenuByMenuID(c fiber.Ctx) error {

result, err := h.menuService.UpdateMenuID(ctx, menuData)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgFailedUpdateMenu)
return common.SendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgFailedUpdateMenu)
}

return SendSuccessResp(c, fiber.StatusOK, "Success", result)
return common.SendSuccessResp(c, fiber.StatusOK, "Success", result)
}

func (h *MenuHandler) UpdateActiveMenuBatchByUserID(c fiber.Ctx) error {
Expand All @@ -121,15 +122,15 @@ func (h *MenuHandler) UpdateActiveMenuBatchByUserID(c fiber.Ctx) error {
userID := c.Params("user_id")
convertUserIDtoInt, err := strconv.Atoi(userID)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

result, err := h.menuService.UpdateActiveMenuBatchUserID(ctx, int64(convertUserIDtoInt))
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, fmt.Sprintf(constants.ErrMsgFailedDeleteMenu, " delete batch by user id"))
return common.SendErrorResp(c, fiber.StatusBadRequest, fmt.Sprintf(constants.ErrMsgFailedDeleteMenu, " delete batch by user id"))
}

return SendSuccessResp(c, fiber.StatusOK, "Success", result)
return common.SendSuccessResp(c, fiber.StatusOK, "Success", result)
}

func (h *MenuHandler) UpdateActiveMenuByMenuID(c fiber.Ctx) error {
Expand All @@ -139,13 +140,13 @@ func (h *MenuHandler) UpdateActiveMenuByMenuID(c fiber.Ctx) error {
menuID := c.Params("menu_id")
convertMenuIDtoInt, err := strconv.Atoi(menuID)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
return common.SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

result, err := h.menuService.UpdateActiveMenuID(ctx, int64(convertMenuIDtoInt))
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, fmt.Sprintf(constants.ErrMsgFailedDeleteMenu, " delete by menu id"))
return common.SendErrorResp(c, fiber.StatusBadRequest, fmt.Sprintf(constants.ErrMsgFailedDeleteMenu, " delete by menu id"))
}

return SendSuccessResp(c, fiber.StatusOK, "Success", result)
return common.SendSuccessResp(c, fiber.StatusOK, "Success", result)
}
2 changes: 1 addition & 1 deletion internal/app/api/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"os"
"testing"

"github.com/voltgizerz/POS-restaurant/internal/app/mocks"
"github.com/voltgizerz/POS-restaurant/internal/mocks"
"github.com/voltgizerz/POS-restaurant/pkg/logger"
"go.uber.org/mock/gomock"
)
Expand Down
2 changes: 1 addition & 1 deletion internal/app/api/middleware/initialization.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/constants"
)

// All request go here first
Expand Down
10 changes: 5 additions & 5 deletions internal/app/api/middleware/jwt_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
"github.com/opentracing/opentracing-go"
"github.com/voltgizerz/POS-restaurant/internal/app/api/handler"
"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/app/api/common"
"github.com/voltgizerz/POS-restaurant/internal/app/ports"
"github.com/voltgizerz/POS-restaurant/internal/constants"
)

const (
Expand All @@ -34,19 +34,19 @@ func (m *JWTAuth) AuthorizeAccess() fiber.Handler {
return func(c fiber.Ctx) error {
authHeader := c.Get(headerAuthName)
if authHeader == "" {
return handler.SendErrorResp(c, fiber.StatusUnauthorized, "Missing Authorization header")
return common.SendErrorResp(c, fiber.StatusUnauthorized, "Missing Authorization header")
}

// Check if the token type is Bearer
tokenType, tokenValue, err := parseAuthHeader(authHeader)
if err != nil || tokenType != tokenTypeJWT {
return handler.SendErrorResp(c, fiber.StatusUnauthorized, "Invalid authorization header format")
return common.SendErrorResp(c, fiber.StatusUnauthorized, "Invalid authorization header format")
}

// Verify JWT token using AuthService.VerifyToken
_, claims, err := m.AuthService.VerifyToken(c.UserContext(), tokenValue)
if err != nil {
return handler.SendErrorResp(c, fiber.StatusUnauthorized, "Invalid token")
return common.SendErrorResp(c, fiber.StatusUnauthorized, "Invalid token")
}

requestID := uuid.New().String()
Expand Down
2 changes: 1 addition & 1 deletion internal/app/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"errors"

"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/constants"
)

type Auth struct {
Expand Down
2 changes: 1 addition & 1 deletion internal/app/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"reflect"
"testing"

"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/constants"
)

func TestGetUserLoginFromCtx(t *testing.T) {
Expand Down
Loading

0 comments on commit e2d8016

Please sign in to comment.