-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
53 lines (43 loc) · 1 KB
/
user.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
package main
import (
"fmt"
"github.com/redis/go-redis/v9"
)
type User struct {
Username string `json:"username" binding:"required"`
Points int `json:"points" binding:"required"`
Rank int `json:"rank"`
}
func (db *Database) SaveUser(user *User) error {
member := redis.Z{
Score: float64(user.Points),
Member: user.Username,
}
pipe := db.Client.TxPipeline()
pipe.ZAdd(Ctx, "leaderboard", member)
rank := pipe.ZRank(Ctx, LeaderboardKey, user.Username)
_, err := pipe.Exec(Ctx)
if err != nil {
return err
}
fmt.Println(rank.Val())
user.Rank = int(rank.Val())
return nil
}
func (db *Database) GetUser(username string) (*User, error) {
pipe := db.Client.TxPipeline()
score := pipe.ZScore(Ctx, LeaderboardKey, username)
rank := pipe.ZRank(Ctx, LeaderboardKey, username)
_, err := pipe.Exec(Ctx)
if err != nil {
return nil, err
}
if score == nil {
return nil, ErrNil
}
return &User{
Username: username,
Points: int(score.Val()),
Rank: int(rank.Val()),
}, nil
}