Skip to content

Commit

Permalink
feat: wrap serveHttp response in cache data
Browse files Browse the repository at this point in the history
Signed-off-by: Matt Gleich <[email protected]>
  • Loading branch information
gleich committed Jan 3, 2025
1 parent c3dfa1f commit b5c9955
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 15 deletions.
15 changes: 9 additions & 6 deletions internal/apis/applemusic/applemusic.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,21 @@ func Setup(router *chi.Mux) {
router.Get("/applemusic", serveHTTP(applemusicCache))
router.Get("/applemusic/playlists/{id}", playlistEndpoint(applemusicCache))
router.Handle("/applemusic/ws", applemusicCache.ServeWS())
go applemusicCache.UpdatePeriodically(cacheUpdate, 30*time.Second)
go applemusicCache.UpdatePeriodically(cacheUpdate, 1*time.Minute)
lumber.Done("setup apple music cache")
}

type cacheDataResponse struct {
PlaylistSummaries []playlistSummary `json:"playlist_summaries"`
RecentlyPlayed []song `json:"recently_played"`
}

func serveHTTP(c *cache.Cache[cacheData]) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
c.DataMutex.RLock()

data := struct {
PlaylistSummaries []playlistSummary `json:"playlist_summaries"`
RecentlyPlayed []song `json:"recently_played"`
}{}
data := cacheDataResponse{}
for _, p := range c.Data.Playlists {
firstFourTracks := []song{}
for _, track := range p.Tracks {
Expand All @@ -99,7 +101,8 @@ func serveHTTP(c *cache.Cache[cacheData]) http.HandlerFunc {
}
data.RecentlyPlayed = c.Data.RecentlyPlayed

err := json.NewEncoder(w).Encode(data)
err := json.NewEncoder(w).
Encode(cache.CacheResponse[cacheDataResponse]{Data: data, Updated: c.Updated})
c.DataMutex.RUnlock()
if err != nil {
lumber.Error(err, "failed to write json data to request")
Expand Down
10 changes: 5 additions & 5 deletions internal/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type Cache[T any] struct {
name string
DataMutex sync.RWMutex
Data T
updated time.Time
Updated time.Time
filePath string
wsConnPool map[*websocket.Conn]bool
wsConnPoolMutex sync.Mutex
Expand All @@ -30,7 +30,7 @@ type Cache[T any] struct {
func New[T any](name string, data T) *Cache[T] {
cache := Cache[T]{
name: name,
updated: time.Now(),
Updated: time.Now(),
filePath: filepath.Join(secrets.SECRETS.CacheFolder, fmt.Sprintf("%s.json", name)),
wsConnPool: make(map[*websocket.Conn]bool),
wsUpgrader: websocket.Upgrader{
Expand All @@ -44,7 +44,7 @@ func New[T any](name string, data T) *Cache[T] {
return &cache
}

type cacheData[T any] struct {
type CacheResponse[T any] struct {
Data T `json:"data"`
Updated time.Time `json:"updated"`
}
Expand All @@ -53,7 +53,7 @@ func (c *Cache[T]) ServeHTTP() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
c.DataMutex.RLock()
err := json.NewEncoder(w).Encode(cacheData[T]{Data: c.Data, Updated: c.updated})
err := json.NewEncoder(w).Encode(CacheResponse[T]{Data: c.Data, Updated: c.Updated})
c.DataMutex.RUnlock()
if err != nil {
lumber.Error(err, "failed to write json data to request")
Expand All @@ -79,7 +79,7 @@ func (c *Cache[T]) Update(data T) {
if string(old) != string(new) && string(new) != "null" && strings.Trim(string(new), " ") != "" {
c.DataMutex.Lock()
c.Data = data
c.updated = time.Now()
c.Updated = time.Now()
c.DataMutex.Unlock()

c.persistToFile()
Expand Down
8 changes: 4 additions & 4 deletions internal/cache/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ func (c *Cache[T]) persistToFile() {
defer file.Close()

c.DataMutex.RLock()
b, err := json.Marshal(cacheData[T]{
b, err := json.Marshal(CacheResponse[T]{
Data: c.Data,
Updated: c.updated,
Updated: c.Updated,
})
c.DataMutex.RUnlock()
if err != nil {
Expand All @@ -54,13 +54,13 @@ func (c *Cache[T]) loadFromFile() {
lumber.Fatal(err, "reading from cache file from", c.filePath, "failed")
}

var data cacheData[T]
var data CacheResponse[T]
err = json.Unmarshal(b, &data)
if err != nil {
lumber.Fatal(err, "unmarshal json data failed from:", string(b))
}

c.Data = data.Data
c.updated = data.Updated
c.Updated = data.Updated
}
}

0 comments on commit b5c9955

Please sign in to comment.