-
Notifications
You must be signed in to change notification settings - Fork 0
/
posts.go
41 lines (37 loc) · 990 Bytes
/
posts.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
package services
import (
"encoding/json"
"github.com/bradfitz/gomemcache/memcache"
"github.com/paudelgaurav/gin-memcache/infrastructure"
"github.com/paudelgaurav/gin-memcache/models"
"github.com/paudelgaurav/gin-memcache/repository"
)
func GetPosts() (posts []models.BlogPost, err error) {
// fetching from cache
// if available, we will unmarshall and return
cachedPosts, err := infrastructure.Cache.Get("posts")
if err == nil {
posts = toBlogPost(cachedPosts.Value)
return posts, err
}
// fetching from db
posts, err = repository.GetPosts()
if err != nil {
return nil, err
}
// storing in cache
cachedData, err := json.Marshal(posts)
if err != nil {
return posts, err
}
if err = infrastructure.Cache.Set(&memcache.Item{Key: "posts", Value: cachedData}); err != nil {
return posts, err
}
return posts, err
}
func toBlogPost(data []byte) (posts []models.BlogPost) {
if err := json.Unmarshal(data, &posts); err != nil {
return posts
}
return posts
}