[GET] /api/groups
回傳值
{
"data": {
"groups": [
{
"id": 1,
"name": "Math", // 群組名稱
"tasks": [
{
"id": 11,
"parent_id": 1,
"name": "Part-1", // 任務名稱
"created_timestamp": 1599058381
}
]
}
]
},
"result": true
}
因為群組、任務列表會很常用到,所以這邊多加一個快取,避免一直存取MySQL
/pkg/redis/redis.go
// Conn Conn
var Conn *redis.Client
// Init Init
func Init() {
Conn = redis.NewClient(&redis.Options{
Addr: config.Val.RedisHost + ":" + config.Val.RedisPort,
Password: config.Val.RedisPass,
DB: 0,
})
_, err := Conn.Ping(context.Background()).Result()
if err != nil {
panic(err)
}
}
群組跟任務有上下層關係,所以很常會跑到兩個迴圈,我盡可能的不超出這範圍
handler/api.go
func findGroups(userID string) (groups []*model.Task, err error) {
// 優先用redis值
val, err := redis.Conn.Get(context.Background(), redisGroupsKey(userID)).Bytes()
if err == nil {
if err = json.Unmarshal(val, &groups); err == nil {
return
}
}
// redis沒有再去讀DB
groups, err = model.TaskModel.GetGroup(userID)
if err != nil {
return
}
// 把值都補到Redis
groupsJSON, _ := json.Marshal(groups)
redis.Conn.Set(context.Background(), redisGroupsKey(userID), groupsJSON, 24*3*time.Hour)
return
}
func findTasks(userID string, parentID []int) (tasks []*model.Task, err error) {
var data []*model.Task
redisCache := false
val, err := redis.Conn.Get(context.Background(), redisTasksKey(userID)).Bytes()
if err == nil {
if err = json.Unmarshal(val, &data); err == nil {
redisCache = true
}
}
if len(data) == 0 {
data, err = model.TaskModel.GetTasks(userID, []int{model.TaskAble})
if err != nil {
return
}
}
if !redisCache {
tasksJSON, _ := json.Marshal(data)
redis.Conn.Set(context.Background(), redisTasksKey(userID), tasksJSON, 24*3*time.Hour)
}
for _, t := range data {
for _, pid := range parentID {
if pid == t.ParentID {
tasks = append(tasks, t)
break
}
}
}
return
}
這支API就差不多完成了
來試打看看
今天的commit
謝謝大家~