Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(api): add in-memory cache for index endpoint
  • Loading branch information
vednoc committed Jul 19, 2021
1 parent eea2abf commit 1242ffd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -15,6 +15,7 @@ require (
github.com/markbates/pkger v0.17.1
github.com/microcosm-cc/bluemonday v1.0.15
github.com/ohler55/ojg v1.10.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/russross/blackfriday/v2 v2.0.1
github.com/userstyles-world/go-chart/v2 v2.4.1
github.com/vednoc/go-usercss-parser v0.9.2
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Expand Up @@ -317,6 +317,8 @@ github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1Cpa
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw=
Expand Down
24 changes: 20 additions & 4 deletions handlers/api/index.go
Expand Up @@ -3,8 +3,10 @@ package api
import (
"fmt"
"strings"
"time"

"github.com/gofiber/fiber/v2"
"github.com/patrickmn/go-cache"

"userstyles.world/models"
)
Expand All @@ -20,6 +22,8 @@ type USoFormat struct {
ID uint `json:"i"`
}

var mem = cache.New(5*time.Minute, 10*time.Minute)

func convertToUSoFormat(s models.APIStyle) USoFormat {
id := fmt.Sprintf("%d", s.ID) // Convert uint to string.

Expand Down Expand Up @@ -71,13 +75,25 @@ func GetStyleIndex(c *fiber.Ctx) error {

// Used by Stylus integration.
if c.Params("format") == "uso-format" {
formattedStyles := make([]USoFormat, len(*styles))
for i, style := range *styles {
formattedStyles[i] = convertToUSoFormat(style)
Convert:
cached, found := mem.Get("index")
if !found {
formatted := make([]USoFormat, len(*styles))
for i, style := range *styles {
formatted[i] = convertToUSoFormat(style)
}

mem.Set("index", formatted, 10*time.Minute)
goto Convert
}

index, ok := cached.([]USoFormat)
if !ok {
goto Convert
}

return c.JSON(fiber.Map{
"data": formattedStyles,
"data": index,
})
}

Expand Down

0 comments on commit 1242ffd

Please sign in to comment.