-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggle_favorite_video.go
48 lines (40 loc) · 1.18 KB
/
toggle_favorite_video.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
package api
import (
"firebase.google.com/go/auth"
"github.com/ham357/youtube-manager-go/middlewares"
"github.com/ham357/youtube-manager-go/models"
"github.com/labstack/echo"
"github.com/valyala/fasthttp"
)
type ToggleFavoriteVideoResponse struct {
VideoId string `json:"video_id"`
IsFavorite bool `json:"is_favorite"`
}
func ToggleFavoriteVideo() echo.HandlerFunc {
return func(c echo.Context) error {
dbs := c.Get("dbs").(*middlewares.DatabaseClient)
videoId := c.Param("id")
token := c.Get("auth").(*auth.Token)
user := models.User{}
if dbs.DB.Table("users").
Where(models.User{UID: token.UID}).First(&user).RecordNotFound() {
user = models.User{UID: token.UID}
dbs.DB.Create(&user)
}
favorite := models.Favorite{}
isFavorite := false
if dbs.DB.Table("favorites").
Where(models.Favorite{UserId: user.ID, VideoId: videoId}).First(&favorite).RecordNotFound() {
favorite = models.Favorite{UserId: user.ID, VideoId: videoId}
dbs.DB.Create(&favorite)
isFavorite = true
} else {
dbs.DB.Delete(&favorite)
}
res := ToggleFavoriteVideoResponse{
VideoId: videoId,
IsFavorite: isFavorite,
}
return c.JSON(fasthttp.StatusOK, res)
}
}