From 8ac21a1046868f097590c5946ff9344c1a779788 Mon Sep 17 00:00:00 2001 From: Reinaldy Rafli Date: Sat, 17 Jul 2021 21:37:01 +0700 Subject: [PATCH] feat(route): get total jokes --- api/app/v1/handler/joke_total.go | 41 ++++++++++++++++++++++++++++++++ api/app/v1/models/response.go | 4 ++-- api/app/v1/routes/joke.go | 5 +++- 3 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 api/app/v1/handler/joke_total.go diff --git a/api/app/v1/handler/joke_total.go b/api/app/v1/handler/joke_total.go new file mode 100644 index 0000000..b95dafc --- /dev/null +++ b/api/app/v1/handler/joke_total.go @@ -0,0 +1,41 @@ +package handler + +import ( + "encoding/json" + "jokes-bapak2-api/app/v1/core" + "jokes-bapak2-api/app/v1/models" + "strconv" + + "github.com/gofiber/fiber/v2" + "github.com/patrickmn/go-cache" +) + +func TotalJokes(c *fiber.Ctx) error { + checkCache := core.CheckJokesCache(memory) + + if !checkCache { + jokes, err := core.GetAllJSONJokes(db) + if err != nil { + return err + } + memory.Set("jokes", jokes, cache.NoExpiration) + } + + jokes, found := memory.Get("jokes") + if !found { + return c.Status(fiber.StatusInternalServerError).JSON(models.Error{ + Error: "no data found", + }) + } + + var data []models.Joke + err := json.Unmarshal(jokes.([]byte), &data) + if err != nil { + return err + } + + dataLength := strconv.Itoa(len(data)) + return c.Status(fiber.StatusOK).JSON(models.ResponseJoke{ + Message: dataLength, + }) +} diff --git a/api/app/v1/models/response.go b/api/app/v1/models/response.go index a942ab7..590536c 100644 --- a/api/app/v1/models/response.go +++ b/api/app/v1/models/response.go @@ -5,6 +5,6 @@ type Error struct { } type ResponseJoke struct { - Link string `json:"link"` - Message string `json:"message"` + Link string `json:"link,omitempty"` + Message string `json:"message,omitempty"` } diff --git a/api/app/v1/routes/joke.go b/api/app/v1/routes/joke.go index 83d4092..e977168 100644 --- a/api/app/v1/routes/joke.go +++ b/api/app/v1/routes/joke.go @@ -15,7 +15,10 @@ func Joke(app *fiber.App) *fiber.App { app.Get("/today", handler.TodayJoke) // Joke by ID - app.Get("/:id", handler.JokeByID) + app.Get("/id/:id", handler.JokeByID) + + // Count total jokes + app.Get("/total", handler.TotalJokes) // Add new joke app.Put("/", middleware.RequireAuth(), handler.AddNewJoke)