This repository has been archived by the owner on May 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
users.go
94 lines (84 loc) · 2.42 KB
/
users.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
88
89
90
91
92
93
94
package busetabot
import (
"context"
"time"
"github.com/pkg/errors"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
const (
KindFavourites = "Favourites"
KindUser = "User"
)
// Favourites contains a user's saved favourites.
type Favourites struct {
Favourites []string
}
type User struct {
LastSeenTime time.Time
Favourites []string
}
type DatastoreUserRepository struct {
}
func (r *DatastoreUserRepository) UpdateUserLastSeenTime(ctx context.Context, userID int, t time.Time) error {
ctx, err := appengine.Namespace(ctx, namespace)
if err != nil {
return err
}
k := datastore.NewKey(ctx, KindUser, "", int64(userID), nil)
e := &User{
LastSeenTime: t,
}
_, err = datastore.Put(ctx, k, e)
if err != nil {
return errors.Wrap(err, "error updating user last seen time")
}
return nil
}
func (r *DatastoreUserRepository) GetUserFavourites(ctx context.Context, userID int) (favourites []string, err error) {
ctx, err = appengine.Namespace(ctx, namespace)
if err != nil {
err = errors.Wrap(err, "error setting namespace")
return
}
k := datastore.NewKey(ctx, KindFavourites, "", int64(userID), nil)
var f Favourites
err = datastore.Get(ctx, k, &f)
if err != nil {
if err != datastore.ErrNoSuchEntity {
err = errors.Wrap(err, "error getting user favourites")
return
}
return nil, nil
}
favourites = f.Favourites
return
}
func (r *DatastoreUserRepository) SetUserFavourites(ctx context.Context, userID int, favourites []string) error {
ctx, err := appengine.Namespace(ctx, namespace)
if err != nil {
return errors.Wrap(err, "error setting namespace")
}
k := datastore.NewKey(ctx, KindFavourites, "", int64(userID), nil)
err = datastore.RunInTransaction(ctx, func(tc context.Context) (err error) {
var f Favourites
err = datastore.Get(tc, k, &f)
if err != nil && err != datastore.ErrNoSuchEntity {
return errors.Wrap(err, "error getting user favourites from datastore")
}
f.Favourites = favourites
_, err = datastore.Put(tc, k, &f)
if err != nil {
return errors.Wrap(err, "error putting user favourites into datastore")
}
return nil
}, nil)
if err != nil {
return errors.Wrap(err, "error updating user favourites in transaction")
}
return nil
}
// GetFormatter returns the user's preferred ETA formatter, or the default ETA formatter.
func (r *DatastoreUserRepository) GetFormatter(ctx context.Context, userID int) Formatter {
return summaryFormatter
}