/
remoteRepository.go
89 lines (77 loc) · 2.26 KB
/
remoteRepository.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package mongo
import (
"context"
"time"
"github.com/pkg/errors"
"go.kicksware.com/api/service-common/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.kicksware.com/api/user-service/core/model"
"go.kicksware.com/api/user-service/core/repo"
)
type remoteRepository struct {
client *mongo.Client
database *mongo.Database
collection *mongo.Collection
timeout time.Duration
}
func NewRemoteRepository(config config.DataStoreConfig) (repo.RemoteRepository, error) {
repo := &remoteRepository{
timeout: time.Duration(config.Timeout) * time.Second,
}
client, err := newMongoClient(config); if err != nil {
return nil, errors.Wrap(err, "repository.NewRemoteRepository")
}
repo.client = client
database := client.Database(config.Database)
repo.database = database
repo.collection = database.Collection(config.Collection)
return repo, nil
}
func (r *remoteRepository) Connect(userID string, remoteID string, provider model.UserProvider) error {
remote := &model.RemoteAuth{
UserID: userID,
RemoteID: remoteID,
Provider: provider,
}
ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
defer cancel()
_, err := r.collection.InsertOne(ctx, remote)
if err != nil {
return errors.Wrap(err, "repository.remote.Connect")
}
return nil
}
func (r *remoteRepository) Sync(userID string, remotes map[model.UserProvider]string) error {
bulk := make([]interface{}, 0)
for provider := range remotes {
bulk = append(bulk, &model.RemoteAuth{
UserID: userID,
RemoteID: remotes[provider],
Provider: provider,
})
}
ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
defer cancel()
_, err := r.collection.InsertMany(ctx, bulk)
if err != nil {
return errors.Wrap(err, "repository.remote.Sync")
}
return nil
}
func (r *remoteRepository) Track(remoteID string, provider model.UserProvider) (string, error) {
filter := bson.M{
"remote_id": remoteID,
"provider": provider,
}
ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
defer cancel()
result := r.collection.FindOne(ctx, filter); if result == nil {
return "", mongo.ErrNoDocuments
}
var remote model.RemoteAuth
if err := result.Decode(&remote); err != nil {
return "", err
}
return remote.UserID, nil
}