onasty/internal/store/rdb/usercache/usercache.go (view raw)
Smirnov Oleksandr
Smirnov Oleksandr
ss2316544@gmail.com feat: implement caching (#40)..., 1 year ago
ss2316544@gmail.com feat: implement caching (#40)..., 1 year ago
| 1 | package usercache |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "strings" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/olexsmir/onasty/internal/store/rdb" |
| 9 | ) |
| 10 | |
| 11 | type UserCacheer interface { |
| 12 | SetIsExists(ctx context.Context, userID string, isExists bool) error |
| 13 | GetIsExists(ctx context.Context, userID string) (isExists bool, err error) |
| 14 | |
| 15 | SetIsActivated(ctx context.Context, userID string, isActivated bool) error |
| 16 | GetIsActivated(ctx context.Context, userID string) (isActivated bool, err error) |
| 17 | } |
| 18 | |
| 19 | var _ UserCacheer = (*UserCache)(nil) |
| 20 | |
| 21 | type UserCache struct { |
| 22 | rdb *rdb.DB |
| 23 | ttl time.Duration |
| 24 | } |
| 25 | |
| 26 | func New(rdb *rdb.DB, ttl time.Duration) *UserCache { |
| 27 | return &UserCache{ |
| 28 | rdb: rdb, |
| 29 | ttl: ttl, |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | func (u *UserCache) SetIsExists(ctx context.Context, userID string, val bool) error { |
| 34 | _, err := u.rdb. |
| 35 | Set(ctx, getKey("exists", userID), val, u.ttl). |
| 36 | Result() |
| 37 | return err |
| 38 | } |
| 39 | |
| 40 | func (u *UserCache) GetIsExists(ctx context.Context, userID string) (bool, error) { |
| 41 | res, err := u.rdb.Get(ctx, getKey(userID, "exists")).Bool() |
| 42 | if err != nil { |
| 43 | return false, err |
| 44 | } |
| 45 | |
| 46 | return res, nil |
| 47 | } |
| 48 | |
| 49 | func (u *UserCache) SetIsActivated(ctx context.Context, userID string, val bool) error { |
| 50 | _, err := u.rdb. |
| 51 | Set(ctx, getKey("activated", userID), val, u.ttl). |
| 52 | Result() |
| 53 | return err |
| 54 | } |
| 55 | |
| 56 | func (u *UserCache) GetIsActivated(ctx context.Context, userID string) (bool, error) { |
| 57 | res, err := u.rdb.Get(ctx, getKey(userID, "activated")).Bool() |
| 58 | if err != nil { |
| 59 | return false, err |
| 60 | } |
| 61 | return res, nil |
| 62 | } |
| 63 | |
| 64 | // getKey return a key for redis in this format user:<userID>:<key> |
| 65 | func getKey(userID, key string) string { |
| 66 | var sb strings.Builder |
| 67 | sb.WriteString("user:") |
| 68 | sb.WriteString(userID) |
| 69 | sb.WriteString(":") |
| 70 | sb.WriteString(key) |
| 71 | return sb.String() |
| 72 | } |