/
repository.go
54 lines (45 loc) · 1.41 KB
/
repository.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
package main
import (
pb "github.com/loogo/wms/vessel-service/proto/vessel"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
dbName = "shippy"
vesselCollection = "vessels"
)
type Repository interface {
FindAvailable(*pb.Specification) (*pb.Vessel, error)
Create(vessel *pb.Vessel) error
Close()
}
type VesselRepository struct {
session *mgo.Session
}
// FindAvailable - checks a specification against a map of vessels,
// if capacity and max weight are below a vessels capacity and max weight,
// then return that vessel.
func (repo *VesselRepository) FindAvailable(spec *pb.Specification) (*pb.Vessel, error) {
var vessel *pb.Vessel
// Here we define a more complex query than our consignment-service's
// GetAll function. Here we're asking for a vessel who's max weight and
// capacity are greater than and equal to the given capacity and weight.
// We're also using the `One` function here as that's all we want.
err := repo.collection().Find(bson.M{
"capacity": bson.M{"$gte": spec.Capacity},
"maxweight": bson.M{"$gte": spec.MaxWeight},
}).One(&vessel)
if err != nil {
return nil, err
}
return vessel, nil
}
func (repo *VesselRepository) Create(vessel *pb.Vessel) error {
return repo.collection().Insert(vessel)
}
func (repo *VesselRepository) Close() {
repo.session.Close()
}
func (repo *VesselRepository) collection() *mgo.Collection {
return repo.session.DB(dbName).C(vesselCollection)
}