aboutsummaryrefslogtreecommitdiff
path: root/api/api.go
blob: 42b9923986484cf896d7587efaa8c508f2bde379 (plain) (blame)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package api

import (
	"net/http"
	"unicode"

	"github.com/gin-gonic/gin"
)

var CONFIG Config

type Config struct {
	JwtSecret           string `toml:"jwt_secret"`
	PasswordResetSecret string `toml:"password_reset_secret"`
	FreeSMSUser         string `toml:"free_sms_user"`
	FreeSMSPass         string `toml:"free_sms_pass"`
}

func SetConfig(config Config) {
	CONFIG = config

	JWT_SECRET = []byte(config.JwtSecret)
	PASSWORD_RESET_SECRET = []byte(config.PasswordResetSecret)
}

type Error struct {
	Code        ErrorCode
	UserMessage string
	err         error
}

func (e Error) Err() error {
	if e.err != nil {
		return e
	}

	return nil
}

func (e Error) Error() string {
	if e.err != nil {
		return e.err.Error()
	}

	return ""
}

func NewInternalError(err error) *Error {
	return &Error{InternalError, "internal error", err}
}

func ToSnake(in string) string {
	runes := []rune(in)
	length := len(runes)

	var out []rune
	for i := 0; i < length; i++ {
		if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
			out = append(out, '_')
		}
		out = append(out, unicode.ToLower(runes[i]))
	}

	return string(out)
}

type Response struct {
	StatusCode Status    `json:"-"`
	ErrorCode  ErrorCode `json:"-"`

	Status   string      `json:"status"`
	Code     string      `json:"code,omitempty"`
	Response interface{} `json:"response,omitempty"`
	Message  string      `json:"message,omitempty"`
}

func (r Response) populateStatus() Response {
	r.Status = ToSnake(r.StatusCode.String())

	if r.ErrorCode != 0 {
		r.Code = ToSnake(r.ErrorCode.String())
	}

	return r
}

func ErrorResponse(code ErrorCode, message string) Response {
	return Response{
		StatusCode: NOK,
		ErrorCode:  code,
		Message:    message,
	}
}

func SuccessResponse(data interface{}) Response {
	return Response{
		StatusCode: OK,
		Response:   data,
	}
}

func WriteJsonResponse(response Response, c *gin.Context) {
	response = response.populateStatus()

	c.JSON(StatusToHttpCode(response.StatusCode, response.ErrorCode), response)
}

func WriteBinary(contentType string, b []byte, c *gin.Context) {
	c.Data(http.StatusOK, contentType, b)
}

type Middleware func(*gin.Context) *Error

func M(handler Middleware) gin.HandlerFunc {
	return func(c *gin.Context) {
		err := handler(c)

		if err != nil {
			WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
			c.Error(err)
			c.Abort()
		} else {
			c.Next()
		}
	}
}

type Query interface {
	ValidateParams() *Error
	Run() (interface{}, *Error)
}

func RunQuery(query Query, c *gin.Context) {
	if err := query.ValidateParams(); err != nil {
		WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
		c.Error(err)
		return
	}

	if out, err := query.Run(); err != nil {
		WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
		c.Error(err)
	} else {
		WriteJsonResponse(SuccessResponse(out), c)
	}
}