diff --git a/backend/handlers/projects.go b/backend/handlers/projects.go index 9f24e64..2c67c70 100644 --- a/backend/handlers/projects.go +++ b/backend/handlers/projects.go @@ -3,9 +3,11 @@ package handlers import ( "fmt" "strconv" + "time" "git.bhasher.com/bhasher/focus/backend/db" "git.bhasher.com/bhasher/focus/backend/types" + "git.bhasher.com/bhasher/focus/backend/utils" "github.com/gofiber/fiber/v2" ) @@ -21,8 +23,16 @@ func projectsRouter(router fiber.Router) error { return nil } +var projectsLastEdit time.Time; + func GetAllProjects(c *fiber.Ctx) error { + isCached, err := utils.Cache(c, projectsLastEdit); + if err == nil && isCached { + return nil; + } + projects, err := db.GetAllProjects() + currentTime := time.Now(); if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ "error": "Cannot retrieve projects", @@ -30,7 +40,13 @@ func GetAllProjects(c *fiber.Ctx) error { }) } - return c.Status(fiber.StatusOK).JSON(projects) + err = c.Status(fiber.StatusOK).JSON(projects) + if err != nil { + return err; + } + + projectsLastEdit = currentTime; + return nil; } func GetProject(c *fiber.Ctx) error { diff --git a/backend/main.go b/backend/main.go index df17f12..a8a9727 100644 --- a/backend/main.go +++ b/backend/main.go @@ -6,7 +6,6 @@ import ( "os" "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/cache" "github.com/gofiber/fiber/v2/middleware/cors" _ "github.com/mattn/go-sqlite3" @@ -37,7 +36,7 @@ func main() { AllowHeaders: "Origin, Content-Type, Accept", })) - app.Use(cache.New()) + // app.Use(cache.New()) handlers.APIRouter(app.Group("/api")) diff --git a/backend/utils/cache.go b/backend/utils/cache.go new file mode 100644 index 0000000..280cb64 --- /dev/null +++ b/backend/utils/cache.go @@ -0,0 +1,21 @@ +package utils + +import ( + "time" + + "github.com/gofiber/fiber/v2" +) + +func Cache(c *fiber.Ctx, lastEdit time.Time) (bool, error) { + clientLast, err := time.Parse(time.RFC1123, c.Get("If-Modified-Since")) + if err != nil { + return false, err + } + + if clientLast.Before(lastEdit) { + c.SendStatus(fiber.StatusNotModified) + return true, nil + } + + return false, nil +} \ No newline at end of file