GetCache gets cached data from Redis.
(c *redis.Client)
| 25 | |
| 26 | // GetCache gets cached data from Redis. |
| 27 | func GetCache(c *redis.Client) (*Cache, error) { |
| 28 | messages, err := c.LRange(context.Background(), "messages", 0, -1).Result() |
| 29 | if err != nil { |
| 30 | return &Cache{}, fmt.Errorf("lrange redis: %v", err) |
| 31 | } |
| 32 | |
| 33 | total, err := c.Get(context.Background(), "total").Int64() |
| 34 | if err == redis.Nil { |
| 35 | total = 0 |
| 36 | } else if err != nil { |
| 37 | return &Cache{}, fmt.Errorf("get redis: %v", err) |
| 38 | } |
| 39 | |
| 40 | msgsCache := make([]Message, 0) // avoid null in JSON when empty |
| 41 | for _, messageJSON := range messages { |
| 42 | var message models.Message |
| 43 | err = json.Unmarshal([]byte(messageJSON), &message) |
| 44 | if err != nil { |
| 45 | return &Cache{}, fmt.Errorf("unmarshal cache: %v", err) |
| 46 | } |
| 47 | |
| 48 | msgsCache = append(msgsCache, Message{ |
| 49 | Message: message, |
| 50 | TimeFmt: timeutil.FormatDuration(message.Time), |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | cache := &Cache{ |
| 55 | Count: int64(len(messages)), |
| 56 | Total: total, |
| 57 | Messages: msgsCache, |
| 58 | } |
| 59 | |
| 60 | return cache, nil |
| 61 | } |
| 62 | |
| 63 | // GetCacheJSON marshals cached data into JSON, |
| 64 | // calls GetCache to get the Cache struct. |
no test coverage detected