/
person.go
70 lines (62 loc) · 1.63 KB
/
person.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
package mongo
import (
"context"
"github.com/Goldwin/ies-pik-cms/pkg/events/entities"
"github.com/Goldwin/ies-pik-cms/pkg/events/repositories"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type Person struct {
ID string `bson:"_id"`
FirstName string `bson:"firstName"`
LastName string `bson:"lastName"`
Birthday string `bson:"birthday"`
}
type personRepositoryImpl struct {
ctx context.Context
db *mongo.Database
}
// GetByIds implements repositories.PersonRepository.
func (p *personRepositoryImpl) GetByIds(ids []string) ([]entities.Person, error) {
result := make([]entities.Person, 0)
res, err := p.db.Collection("persons").Find(p.ctx, bson.M{"_id": bson.M{"$in": ids}})
if err != nil {
return nil, err
}
defer res.Close(p.ctx)
for res.Next(p.ctx) {
var model Person
if err := res.Decode(&model); err != nil {
return nil, err
}
result = append(result, entities.Person{
ID: model.ID,
FirstName: model.FirstName,
LastName: model.LastName,
Birthday: model.Birthday,
})
}
return result, nil
}
// Get implements PersonRepository.
func (p *personRepositoryImpl) Get(id string) (*entities.Person, error) {
var model Person
err := p.db.Collection("persons").FindOne(p.ctx, bson.M{"_id": id}).Decode(&model)
if err == mongo.ErrNoDocuments {
return nil, nil
}
if err != nil {
return nil, err
}
return &entities.Person{
ID: model.ID,
FirstName: model.FirstName,
LastName: model.LastName,
}, nil
}
func NewPersonRepository(ctx context.Context, db *mongo.Database) repositories.PersonRepository {
return &personRepositoryImpl{
ctx: ctx,
db: db,
}
}