Get some amount of random bookmarks

This commit is contained in:
2022-12-11 16:22:24 +03:00
parent 7674557182
commit be36ed3593
5 changed files with 78 additions and 22 deletions

View File

@ -72,6 +72,7 @@ func (s Store[T]) GetMany(ctx context.Context, filter *bson.D) ([]*T, error) {
}
return res, nil
}
func (s Store[T]) DeleteByID(ctx context.Context, id primitive.ObjectID) error {
_, err := s.Coll.DeleteOne(ctx, bson.D{{Key: "_id", Value: id}})
return err
@ -81,10 +82,3 @@ func (s Store[T]) ReplaceByID(ctx context.Context, id primitive.ObjectID, item *
_, err := s.Coll.ReplaceOne(ctx, bson.D{{Key: "_id", Value: id}}, item)
return err
}
func getFilter(f *bson.D) bson.D {
if f == nil {
return bson.D{}
}
return *f
}

View File

@ -2,6 +2,9 @@ package storage
import (
"context"
"log"
"net/url"
"strings"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
@ -96,6 +99,23 @@ func (m MongodbStorage) GetBookmarks(filter *bson.D) ([]*Bookmark, error) {
return store.GetMany(ctx, filter)
}
func (m MongodbStorage) GetRandomBookmarks(count int, filter *bson.D) ([]*Bookmark, error) {
passedFilter := getFilter(filter)
ctx := context.TODO()
store := NewStore[Bookmark](&m, "bookmarks")
bookmarks := []*Bookmark{}
cur, err := store.Coll.Aggregate(ctx, bson.A{
bson.D{{Key: "$match", Value: passedFilter}},
bson.D{{Key: "$sample", Value: bson.D{bson.E{Key: "size", Value: count}}}},
})
if err != nil {
log.Println("Cant aggregate random bookmakrs: ", err)
return bookmarks, err
}
cur.All(ctx, &bookmarks)
return bookmarks, err
}
func (m MongodbStorage) GetUserBookmarks(user *User, filter *bson.D) ([]*Bookmark, error) {
passedFilter := getFilter(filter)
f := bson.D{{Key: "userid", Value: user.Id}}
@ -108,3 +128,27 @@ func (m MongodbStorage) GetUserBookmarks(user *User, filter *bson.D) ([]*Bookmar
func (m MongodbStorage) Collection(col string) *mongo.Collection {
return m.Db.Database("nash").Collection(col)
}
func getFilter(f *bson.D) bson.D {
if f == nil {
return bson.D{}
}
return *f
}
func QueryFilter(q *url.Values) bson.D {
filter := bson.D{}
for k, v := range *q {
var f bson.E
q := strings.Split(k, "_")
if len(q) == 1 { // If param is like "name" or "url" we're using exact matching
f = bson.E{Key: k, Value: v[0]}
} else {
if q[1] == "like" { // If it's like "name_like", we're using regex
f = bson.E{Key: q[0], Value: bson.D{{Key: "$regex", Value: v[0]}}}
}
}
filter = append(filter, f) // Applying query filters to user filter
}
return filter
}