-
Notifications
You must be signed in to change notification settings - Fork 0
/
room_store.go
61 lines (51 loc) · 1.43 KB
/
room_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
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"
)
type RoomStore interface {
InsertRoom(context.Context, *types.Room) (*types.Room, error)
GetRooms(context.Context, bson.M) ([]*types.Room, error)
}
type MongoRoomStore struct {
client *mongo.Client
coll *mongo.Collection
HotelStore
}
func NewMongoRoomStore(client *mongo.Client, hotelStore HotelStore) *MongoRoomStore {
dbname := os.Getenv(MongoDBNameEnvName)
return &MongoRoomStore{
client: client,
coll: client.Database(dbname).Collection("rooms"),
HotelStore: hotelStore,
}
}
func (s *MongoRoomStore) GetRooms(ctx context.Context, filter bson.M) ([]*types.Room, error) {
resp, err := s.coll.Find(ctx, filter)
if err != nil {
return nil, err
}
var rooms []*types.Room
if err := resp.All(ctx, &rooms); err != nil {
return nil, err
}
return rooms, nil
}
func (s *MongoRoomStore) InsertRoom(ctx context.Context, room *types.Room) (*types.Room, error) {
resp, err := s.coll.InsertOne(ctx, room)
if err != nil {
return nil, err
}
room.ID = resp.InsertedID.(primitive.ObjectID)
// update the hotel with this room id
filter := Map{"_id": room.HotelID}
update := Map{"$push": bson.M{"rooms": room.ID}}
if err := s.HotelStore.Update(ctx, filter, update); err != nil {
return nil, err
}
return room, nil
}