From be88c02d99e3bd0434f721ad1a5cdbefc6558751 Mon Sep 17 00:00:00 2001 From: orangix Date: Mon, 14 Aug 2023 22:49:04 +0200 Subject: [PATCH] add cache, fix query --- api/trending.go | 44 +++++++++++++++++++++++++++----------------- views/trending.hbs | 2 +- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/api/trending.go b/api/trending.go index 2026f8f..f6f38a0 100644 --- a/api/trending.go +++ b/api/trending.go @@ -1,39 +1,35 @@ package api import ( - "io/ioutil" + "fmt" + "io" "net/http" + "os" "strings" "sync" + "codeberg.org/rimgo/rimgo/utils" + "github.com/patrickmn/go-cache" "github.com/tidwall/gjson" ) func (client *Client) FetchTrending(section, sort, page string) ([]Submission, error) { - req, err := http.NewRequest("GET", "https://api.imgur.com/post/v1/posts?client_id="+client.ClientID+"&filter[section]=eq:"+section+"&include=cover,viral&page=1", nil) + cacheData, found := client.Cache.Get(fmt.Sprintf("trending-%s-%s-%s", section, sort, page)) + if found { + return cacheData.([]Submission), nil + } + + req, err := http.NewRequest("GET", "https://api.imgur.com/post/v1/posts", nil) if err != nil { return []Submission{}, err } + utils.SetReqHeaders(req) q := req.URL.Query() q.Add("client_id", client.ClientID) q.Add("include", "cover") q.Add("page", page) - switch section { - case "hot": - q.Add("filter[section]", "eq:hot") - q.Add("sort", "-viral") - case "new": - q.Add("filter[section]", "eq:new") - q.Add("sort", "-viral") - case "top": - q.Add("filter[section]", "eq:top") - q.Add("sort", "-viral") - default: - q.Add("filter[section]", "eq:hot") - section = "hot" - } switch sort { case "newest": q.Add("filter[window]", "week") @@ -48,6 +44,18 @@ func (client *Client) FetchTrending(section, sort, page string) ([]Submission, e q.Add("sort", "-viral") sort = "popular" } + switch section { + case "hot": + q.Add("filter[section]", "eq:hot") + case "new": + q.Add("filter[section]", "eq:new") + case "top": + q.Add("filter[section]", "eq:top") + q.Add("filter[window]", "day") + default: + q.Add("filter[section]", "eq:hot") + section = "hot" + } req.URL.RawQuery = q.Encode() @@ -56,11 +64,12 @@ func (client *Client) FetchTrending(section, sort, page string) ([]Submission, e return []Submission{}, err } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return []Submission{}, err } + os.Stdout.Write(body) data := gjson.Parse(string(body)) wg := sync.WaitGroup{} @@ -95,6 +104,7 @@ func (client *Client) FetchTrending(section, sort, page string) ([]Submission, e wg.Wait() + client.Cache.Set(fmt.Sprintf("trending-%s-%s-%s", section, sort, page), posts, cache.DefaultExpiration) // TODO: Cache trending // client.Cache.Set(tag+sort+page+"-tag", tagData, cache.DefaultExpiration) return posts, nil diff --git a/views/trending.hbs b/views/trending.hbs index 76a5cc6..476e2e1 100644 --- a/views/trending.hbs +++ b/views/trending.hbs @@ -2,7 +2,7 @@ - {{query}} - rimgo + Trending - rimgo {{> partials/head }}