-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.go
64 lines (56 loc) · 1.47 KB
/
utils.go
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
package api
import (
"net/http"
"strconv"
"github.com/billy4479/telegram-storage/backend/db"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
func returnErrorJSON(c echo.Context, code int, err error) error {
if err != nil {
return c.JSON(code, echo.Map{"status": code, "message": err.Error()})
}
return nil
}
func getIDAndUserIDFromContext(c echo.Context) (uint64, int64, error) {
idStr := c.QueryParam("id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
return 0, 0, returnErrorJSON(c, http.StatusBadRequest, err)
}
userid, err := getUserIDFromContext(c)
if err != nil {
return 0, 0, returnErrorJSON(c, http.StatusUnauthorized, err)
}
return id, userid, nil
}
func handleDBErr(c echo.Context, err error) error {
if err == gorm.ErrRecordNotFound {
if errJ := returnErrorJSON(c, http.StatusNotFound, err); errJ != nil {
return errJ
}
return err
}
if err == db.ErrUserAlreadyExists {
if errJ := returnErrorJSON(c, http.StatusConflict, err); errJ != nil {
return errJ
}
return err
}
if err == db.ErrNonEmptyFolder {
if errJ := returnErrorJSON(c, http.StatusBadRequest, err); errJ != nil {
return errJ
}
return err
}
if err == db.ErrCannotCreateFolder || err == db.ErrAlreadyExists || err == db.ErrInvalidPath {
if errJ := returnErrorJSON(c, http.StatusBadRequest, err); errJ != nil {
return errJ
}
return err
}
if errJ := returnErrorJSON(c, http.StatusInternalServerError, err); errJ != nil {
return errJ
}
return err
}