File size: 1,949 Bytes
e935eae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package controller

import (
	models "github.com/abdanhafidz/ai-visual-multi-modal-backend/models"
	services "github.com/abdanhafidz/ai-visual-multi-modal-backend/services"
	utils "github.com/abdanhafidz/ai-visual-multi-modal-backend/utils"
	"github.com/gin-gonic/gin"
)

type (
	Controller interface {
		HeaderParse(ctx *gin.Context)
		RequestJSON(ctx *gin.Context, request any)
		Response(ctx *gin.Context, res any)
	}
	controller[TService services.Service] struct {
		accountData models.AccountData
		service     TService
	}
)

func (c *controller[TService]) HeaderParse(ctx *gin.Context) {
	cParam, _ := ctx.Get("account_data")
	if cParam != nil {
		c.accountData = cParam.(models.AccountData)
	}
}

func (c *controller[TService]) RequestJSON(ctx *gin.Context, request any) {
	cParam, _ := ctx.Get("AccountData")
	if cParam != nil {
		c.accountData = cParam.(models.AccountData)
	}

	errBinding := ctx.ShouldBindJSON(&request)
	if errBinding != nil {
		utils.ResponseFAIL(ctx, 400, models.Exception{
			BadRequest: true,
			Message:    "Invalid Request!, recheck your request, there's must be some problem about required parameter or type parameter",
		})
		return
	}
}

func (c *controller[TService]) Response(ctx *gin.Context, res any) {
	switch {
	case c.service.Error() != nil:
		utils.ResponseFAIL(ctx, 500, models.Exception{
			InternalServerError: true,
			Message:             "Internal Server Error",
		})
		utils.LogError(c.service.Error())
	case c.service.Exception().DataDuplicate:
		utils.ResponseFAIL(ctx, 400, c.service.Exception())
	case c.service.Exception().Unauthorized:
		utils.ResponseFAIL(ctx, 401, c.service.Exception())
	case c.service.Exception().DataNotFound:
		utils.ResponseFAIL(ctx, 404, c.service.Exception())
	case c.service.Exception().Message != "":
		utils.ResponseFAIL(ctx, 400, c.service.Exception())
	default:
		utils.ResponseOK(ctx, res)
	}
}