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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
package shortcuts
import (
"shrine/enums"
"shrine/types/common"
"shrine/types/hypertext"
"github.com/gofiber/fiber/v2"
)
func Respond(context *fiber.Ctx, data any) *Response {
return &Response{
Context: context,
Data: data,
Status: fiber.StatusOK,
}
}
func (self *Response) As(status int) error {
self.Status = status
if self.Data == nil {
return self.Context.SendStatus(status)
}
return self.Context.Status(status).JSON(self.Data)
}
func HandleError(context *fiber.Ctx, err *hypertext.ServiceError) error {
statusMap := map[enums.ErrorKind]int{
enums.BadRequest: fiber.StatusBadRequest,
enums.Unauthorized: fiber.StatusUnauthorized,
enums.Forbidden: fiber.StatusForbidden,
enums.NotFound: fiber.StatusNotFound,
enums.Conflict: fiber.StatusConflict,
enums.Unprocessable: fiber.StatusUnprocessableEntity,
enums.TooManyRequest: fiber.StatusTooManyRequests,
enums.Internal: fiber.StatusInternalServerError,
}
status, exists := statusMap[err.Kind]
if !exists {
status = fiber.StatusInternalServerError
}
return Respond(context, common.ErrorResponse{
Error: err.Message,
}).As(status)
}
func BadRequest(context *fiber.Ctx, err error) error {
return Respond(context, common.ErrorResponse{
Error: err.Error(),
}).As(fiber.StatusBadRequest)
}
func Unauthorized(context *fiber.Ctx, err error) error {
return Respond(context, common.ErrorResponse{
Error: err.Error(),
}).As(fiber.StatusUnauthorized)
}
func Forbidden(context *fiber.Ctx, err error) error {
return Respond(context, common.ErrorResponse{
Error: err.Error(),
}).As(fiber.StatusForbidden)
}
func NotFound(context *fiber.Ctx, err error) error {
return Respond(context, common.ErrorResponse{
Error: err.Error(),
}).As(fiber.StatusNotFound)
}
func InternalServerError(context *fiber.Ctx, err error) error {
return Respond(context, common.ErrorResponse{
Error: err.Error(),
}).As(fiber.StatusInternalServerError)
}
func Success(context *fiber.Ctx, data any) error {
return Respond(context, data).As(fiber.StatusOK)
}
func Created(context *fiber.Ctx, data any) error {
return Respond(context, data).As(fiber.StatusCreated)
}
func NoContent(context *fiber.Ctx) error {
return Respond(context, nil).As(fiber.StatusNoContent)
}
|