File size: 1,857 Bytes
98c95a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
package controller

import (
	"api.qobiltu.id/models"
	"api.qobiltu.id/services"
	"api.qobiltu.id/utils"
	"github.com/gin-gonic/gin"
)

type (
	Controllers interface {
		RequestJSON(c *gin.Context)
		Response(c *gin.Context)
	}
	Controller[T1 any, T2 any, T3 any] struct {
		AccountData models.AccountData
		Request     T1
		Service     *services.Service[T2, T3]
	}
)

func (controller *Controller[T1, T2, T3]) HeaderParse(c *gin.Context, act func()) {
	cParam, _ := c.Get("accountData")
	if cParam != nil {
		controller.AccountData = cParam.(models.AccountData)
	}
	act()
}
func (controller *Controller[T1, T2, T3]) RequestJSON(c *gin.Context, act func()) {
	cParam, _ := c.Get("accountData")
	if cParam != nil {
		controller.AccountData = cParam.(models.AccountData)
	}
	errBinding := c.ShouldBindJSON(&controller.Request)
	if errBinding != nil {
		ResponseFAIL(c, 400, models.Exception{
			BadRequest: true,
			Message:    "Invalid Request!, recheck your request, there's must be some problem about required parameter or type parameter",
		})
		return
	} else {
		act()
		controller.Response(c)
	}
}
func (controller *Controller[T1, T2, T3]) Response(c *gin.Context) {
	switch {
	case controller.Service.Error != nil:
		utils.LogError(controller.Service.Error)
		ResponseFAIL(c, 500, models.Exception{
			InternalServerError: true,
			Message:             "Internal Server Error",
		})
	case controller.Service.Exception.DataDuplicate:
		ResponseFAIL(c, 400, controller.Service.Exception)
	case controller.Service.Exception.Unauthorized:
		ResponseFAIL(c, 401, controller.Service.Exception)
	case controller.Service.Exception.DataNotFound:
		ResponseFAIL(c, 404, controller.Service.Exception)
	case controller.Service.Exception.Message != "":
		ResponseFAIL(c, 400, controller.Service.Exception)
	default:
		ResponseOK(c, controller.Service.Result)
	}
}