-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathuser.go
90 lines (76 loc) · 1.89 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
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
package org
import (
"context"
"fmt"
"time"
"github.com/go-redis/cache/v8"
"github.com/uptrace/go-realworld-example-app/rwe"
)
type User struct {
tableName struct{} `pg:",alias:u"`
ID uint64 `json:"-"`
Username string `json:"username"`
Email string `json:"email"`
Bio string `json:"bio"`
Image string `json:"image"`
Password string `pg:"-" json:"password,omitempty"`
PasswordHash string `json:"-"`
Following bool `pg:"-" json:"following"`
Token string `pg:"-" json:"token,omitempty"`
}
type FollowUser struct {
tableName struct{} `pg:"alias:fu"`
UserID uint64
FollowedUserID uint64
}
type Profile struct {
tableName struct{} `pg:"users,alias:u"`
ID uint64 `json:"-"`
Username string `json:"username"`
Bio string `json:"bio"`
Image string `json:"image"`
Following bool `pg:"-" json:"following"`
}
func NewProfile(user *User) *Profile {
return &Profile{
Username: user.Username,
Bio: user.Bio,
Image: user.Image,
Following: user.Following,
}
}
func SelectUser(ctx context.Context, userID uint64) (*User, error) {
user := new(User)
if err := rwe.RedisCache().Once(&cache.Item{
Ctx: ctx,
Key: fmt.Sprintf("user:%d", userID),
Value: user,
TTL: 15 * time.Minute,
Do: func(item *cache.Item) (interface{}, error) {
return selectUser(ctx, userID)
},
}); err != nil {
return nil, err
}
return user, nil
}
func selectUser(ctx context.Context, id uint64) (*User, error) {
user := new(User)
if err := rwe.PGMain().
ModelContext(ctx, user).
Where("id = ?", id).
Select(); err != nil {
return nil, err
}
return user, nil
}
func SelectUserByUsername(ctx context.Context, username string) (*User, error) {
user := new(User)
if err := rwe.PGMain().
ModelContext(ctx, user).
Where("username = ?", username).
Select(); err != nil {
return nil, err
}
return user, nil
}