Nashboard/storage/mongoStore.go

85 lines
2.0 KiB
Go
Raw Normal View History

2022-12-11 02:05:03 +03:00
package storage
import (
"context"
"log"
"reflect"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
func NewStore[T any](db *MongodbStorage, collection string) Store[T] {
return Store[T]{
Db: db.Db,
Coll: db.Collection(collection),
}
}
type Store[T any] struct {
Db *mongo.Client
Coll *mongo.Collection
}
func (s Store[T]) InsertOne(ctx context.Context, item *T) (primitive.ObjectID, error) {
result, err := s.Coll.InsertOne(ctx, item)
if err != nil {
if e, ok := err.(mongo.WriteError); ok {
log.Printf("Error writing new item of type %v: %v ", reflect.TypeOf(item), e)
return primitive.NilObjectID, e
}
log.Printf("Error creating new item of type %v: %v ", reflect.TypeOf(item), err)
return primitive.NilObjectID, err
}
rid, _ := result.InsertedID.(primitive.ObjectID)
return rid, nil
}
func (s Store[T]) GetById(ctx context.Context, id primitive.ObjectID) (*T, error) {
res := s.Coll.FindOne(ctx, bson.D{{Key: "_id", Value: id}})
if res.Err() != nil {
return nil, res.Err()
}
var item T
res.Decode(&item)
return &item, nil
}
func (s Store[T]) GetOne(ctx context.Context, filter *bson.D) (*T, error) {
f := getFilter(filter)
res := s.Coll.FindOne(ctx, f)
if res.Err() != nil {
return nil, res.Err()
}
var item T
res.Decode(&item)
return &item, nil
}
func (s Store[T]) GetMany(ctx context.Context, filter *bson.D) ([]*T, error) {
f := getFilter(filter)
cur, err := s.Coll.Find(ctx, f)
if err != nil {
log.Println("Error fetching items: ", err)
return nil, err
}
res := []*T{}
2022-12-11 02:05:03 +03:00
err = cur.All(ctx, &res)
if err != nil {
log.Println("Error collecting items to slice: ", err)
return nil, err
}
return res, nil
}
2022-12-11 16:22:24 +03:00
2022-12-11 02:05:03 +03:00
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
}
func (s Store[T]) ReplaceByID(ctx context.Context, id primitive.ObjectID, item *T) error {
_, err := s.Coll.ReplaceOne(ctx, bson.D{{Key: "_id", Value: id}}, item)
return err
}