1
0
mirror of https://github.com/ebosas/microservices.git synced 2025-06-06 22:16:11 +02:00

79 lines
1.8 KiB
Go
Raw Normal View History

2021-10-07 16:23:34 +03:00
package cache
import (
"context"
"encoding/json"
"fmt"
"github.com/ebosas/microservices/internal/models"
2021-10-10 18:49:39 +03:00
"github.com/ebosas/microservices/internal/timeutil"
2021-10-07 16:23:34 +03:00
"github.com/go-redis/redis/v8"
)
2021-10-10 18:49:39 +03:00
// Message adds additional fields to models.Message.
type Message struct {
models.Message
TimeFmt string `json:"timefmt"`
}
// Cache is used in the messages.html template.
2021-10-07 16:23:34 +03:00
type Cache struct {
2021-10-10 18:49:39 +03:00
Count int64 `json:"count"`
Total int64 `json:"total"`
Messages []Message `json:"messages"`
2021-10-07 16:23:34 +03:00
}
2021-10-10 18:49:39 +03:00
// GetCache gets cached data from Redis.
func GetCache(c *redis.Client) (*Cache, error) {
messages, err := c.LRange(context.Background(), "messages", 0, -1).Result()
2021-10-07 16:23:34 +03:00
if err != nil {
2021-10-10 18:49:39 +03:00
return &Cache{}, fmt.Errorf("lrange redis: %v", err)
2021-10-07 16:23:34 +03:00
}
2021-10-10 18:49:39 +03:00
total, err := c.Get(context.Background(), "total").Int64()
if err == redis.Nil {
total = 0
} else if err != nil {
return &Cache{}, fmt.Errorf("get redis: %v", err)
}
2021-10-11 08:56:44 +03:00
msgsCache := make([]Message, 0) // avoid null in JSON when empty
2021-10-10 18:49:39 +03:00
for _, messageJSON := range messages {
var message models.Message
err = json.Unmarshal([]byte(messageJSON), &message)
if err != nil {
return &Cache{}, fmt.Errorf("unmarshal cache: %v", err)
}
msgsCache = append(msgsCache, Message{
Message: message,
2021-11-03 16:54:40 +02:00
TimeFmt: timeutil.FormatDuration(message.Time),
2021-10-10 18:49:39 +03:00
})
2021-10-07 16:23:34 +03:00
}
2021-10-10 18:49:39 +03:00
cache := &Cache{
Count: int64(len(messages)),
Total: total,
Messages: msgsCache,
}
return cache, nil
2021-10-07 16:23:34 +03:00
}
2021-10-10 18:49:39 +03:00
// GetCacheJSON marshals cached data into JSON,
// calls GetCache to get the Cache struct.
2021-10-07 16:23:34 +03:00
func GetCacheJSON(c *redis.Client) (string, error) {
2021-10-10 18:49:39 +03:00
cacheData, err := GetCache(c)
2021-10-07 16:23:34 +03:00
if err != nil {
2021-10-10 18:49:39 +03:00
return "", fmt.Errorf("get cache: %s", err)
2021-10-07 16:23:34 +03:00
}
2021-10-10 18:49:39 +03:00
cacheJSON, err := json.Marshal(cacheData)
if err != nil {
return "", fmt.Errorf("marshal cache: %s", err)
2021-10-07 16:23:34 +03:00
2021-10-10 18:49:39 +03:00
}
2021-10-07 16:23:34 +03:00
2021-10-10 18:49:39 +03:00
return string(cacheJSON), nil
2021-10-07 16:23:34 +03:00
}