2022-12-11 15:28:10 +03:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2022-12-11 16:22:24 +03:00
|
|
|
"strconv"
|
2022-12-11 15:28:10 +03:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.nefrace.ru/nefrace/nashboard/storage"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
|
|
)
|
|
|
|
|
|
|
|
type newBookmarkForm struct {
|
|
|
|
Name string
|
|
|
|
Url string
|
|
|
|
FolderID primitive.ObjectID
|
|
|
|
Tags []string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Server) handleNewBookmark(c Context) error {
|
|
|
|
var form newBookmarkForm
|
|
|
|
err := DecodeJSON(c.R.Body, &form)
|
|
|
|
if err != nil {
|
|
|
|
return ApiError{Err: "can't decode json to bookmark: " + err.Error(), Status: 400}
|
|
|
|
}
|
|
|
|
ctx := c.R.Context()
|
|
|
|
user := ctx.Value(CtxValue("user")).(*storage.User)
|
|
|
|
bookmark := storage.Bookmark{
|
|
|
|
Id: primitive.NewObjectID(),
|
|
|
|
Name: form.Name,
|
|
|
|
Url: form.Url,
|
|
|
|
FolderID: form.FolderID,
|
|
|
|
Tags: form.Tags,
|
|
|
|
UserID: user.Id,
|
|
|
|
Created: time.Now(),
|
|
|
|
}
|
|
|
|
_, err = s.Db.CreateBookmark(&bookmark)
|
|
|
|
if err != nil {
|
|
|
|
return ApiError{Err: "can't safe bookmark: " + err.Error(), Status: 500}
|
|
|
|
}
|
|
|
|
return c.WriteJSON(201, &bookmark)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Server) handleGetBookmarks(c Context) error {
|
|
|
|
ctx := c.R.Context()
|
|
|
|
user := ctx.Value(CtxValue("user")).(*storage.User) // Getting currently logged in user
|
|
|
|
query := c.R.URL.Query()
|
2022-12-11 16:22:24 +03:00
|
|
|
filter := storage.QueryFilter(&query)
|
|
|
|
filter = append(filter, bson.E{Key: "userid", Value: user.Id})
|
|
|
|
log.Println(filter)
|
2022-12-11 15:28:10 +03:00
|
|
|
bookmarks, err := s.Db.GetBookmarks(&filter)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error getting bookmarks: ", err)
|
|
|
|
c.WriteJSON(200, []*storage.Bookmark{})
|
|
|
|
}
|
|
|
|
return c.WriteJSON(200, bookmarks)
|
|
|
|
}
|
2022-12-11 16:22:24 +03:00
|
|
|
|
|
|
|
func (s Server) handleGetRandomBookmarks(c Context) error {
|
|
|
|
ctx := c.R.Context()
|
|
|
|
user := ctx.Value(CtxValue("user")).(*storage.User)
|
|
|
|
countVar := c.GetVar("count")
|
|
|
|
count, err := strconv.Atoi(countVar)
|
|
|
|
if err != nil {
|
|
|
|
count = 1
|
|
|
|
}
|
|
|
|
bookmarks, err := s.Db.GetRandomBookmarks(count, &bson.D{{Key: "userid", Value: user.Id}})
|
|
|
|
if err != nil {
|
|
|
|
return ApiError{Err: "can't get bookmarks: " + err.Error(), Status: 400}
|
|
|
|
}
|
|
|
|
return c.WriteJSON(200, bookmarks)
|
|
|
|
}
|