-
Notifications
You must be signed in to change notification settings - Fork 0
/
hotel_store.go
73 lines (64 loc) · 1.91 KB
/
hotel_store.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
65
66
67
68
69
70
71
72
73
package db
import (
"context"
"os"
"github.com/mexirica/hotel-reservation/types"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type HotelStore interface {
InsertHotel(context.Context, *types.Hotel) (*types.Hotel, error)
Update(context.Context, Map, Map) error
GetHotels(context.Context, Map, *Pagination) ([]*types.Hotel, error)
GetHotelByID(context.Context, string) (*types.Hotel, error)
}
type MongoHotelStore struct {
client *mongo.Client
coll *mongo.Collection
}
func NewMongoHotelStore(client *mongo.Client) *MongoHotelStore {
dbname := os.Getenv(MongoDBNameEnvName)
return &MongoHotelStore{
client: client,
coll: client.Database(dbname).Collection("hotels"),
}
}
func (s *MongoHotelStore) GetHotelByID(ctx context.Context, id string) (*types.Hotel, error) {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, err
}
var hotel types.Hotel
if err := s.coll.FindOne(ctx, bson.M{"_id": oid}).Decode(&hotel); err != nil {
return nil, err
}
return &hotel, nil
}
func (s *MongoHotelStore) GetHotels(ctx context.Context, filter Map, pag *Pagination) ([]*types.Hotel, error) {
opts := options.FindOptions{}
opts.SetSkip((pag.Page - 1) * pag.Limit)
opts.SetLimit(pag.Limit)
resp, err := s.coll.Find(ctx, filter, &opts)
if err != nil {
return nil, err
}
var hotels []*types.Hotel
if err := resp.All(ctx, &hotels); err != nil {
return nil, err
}
return hotels, nil
}
func (s *MongoHotelStore) Update(ctx context.Context, filter Map, update Map) error {
_, err := s.coll.UpdateOne(ctx, filter, update)
return err
}
func (s *MongoHotelStore) InsertHotel(ctx context.Context, hotel *types.Hotel) (*types.Hotel, error) {
resp, err := s.coll.InsertOne(ctx, hotel)
if err != nil {
return nil, err
}
hotel.ID = resp.InsertedID.(primitive.ObjectID)
return hotel, nil
}