From fcab9458eeee4d23c92e9eca6d781c4753dd3646 Mon Sep 17 00:00:00 2001 From: Caleb Gardner Date: Wed, 4 Sep 2024 21:22:52 -0500 Subject: [PATCH] Blog cache --- internal/blog/blog.go | 19 +++++++++++++++++-- internal/blog/main.go | 6 ++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/internal/blog/blog.go b/internal/blog/blog.go index 924e950..47cf5e5 100644 --- a/internal/blog/blog.go +++ b/internal/blog/blog.go @@ -28,7 +28,6 @@ type Blog struct { } func (b *BlogApp) ConvertBlog(blog *Blog) { - //TODO: parse BBCode/Markdown from blog if !blog.StaticPage { blog.Blog = b.conv.HTMLConvert(blog.Blog) } @@ -48,6 +47,12 @@ func (b *BlogApp) GetAuthor(blog *Blog) (*Author, error) { } func (b *BlogApp) Blog(ID string) (*Blog, error) { + b.cacheMutex.RLock() + blog, has := b.blogCache[ID] + b.cacheMutex.RUnlock() + if has { + return &blog, nil + } res := b.blogCol.FindOne(context.Background(), bson.M{"_id": ID, "draft": false}) if res.Err() != nil { if res.Err() == mongo.ErrNoDocuments { @@ -55,15 +60,25 @@ func (b *BlogApp) Blog(ID string) (*Blog, error) { } return nil, res.Err() } - var blog Blog err := res.Decode(&blog) if err != nil { return nil, err } b.ConvertBlog(&blog) + b.cacheMutex.Lock() + b.blogCache[ID] = blog + b.cacheMutex.Unlock() + go b.CleanCache(ID) return &blog, nil } +func (b *BlogApp) CleanCache(ID string) { + time.Sleep(5 * time.Minute) + b.cacheMutex.Lock() + delete(b.blogCache, ID) + b.cacheMutex.Unlock() +} + func (b *BlogApp) reqBlog(w http.ResponseWriter, r *http.Request) { blogID := r.PathValue("blogID") if blogID == "" { diff --git a/internal/blog/main.go b/internal/blog/main.go index d13699b..068e856 100644 --- a/internal/blog/main.go +++ b/internal/blog/main.go @@ -2,6 +2,7 @@ package blog import ( "net/http" + "sync" "github.com/CalebQ42/bbConvert" "github.com/CalebQ42/darkstorm-server/internal/backend" @@ -14,6 +15,9 @@ type BlogApp struct { authCol *mongo.Collection portfolioCol *mongo.Collection conv bbConvert.ComboConverter + + cacheMutex *sync.RWMutex + blogCache map[string]Blog } func NewBlogApp(db *mongo.Database) *BlogApp { @@ -22,6 +26,8 @@ func NewBlogApp(db *mongo.Database) *BlogApp { authCol: db.Collection("author"), portfolioCol: db.Collection("portfolio"), conv: bbConvert.NewComboConverter(), + cacheMutex: &sync.RWMutex{}, + blogCache: make(map[string]Blog), } return out }