feat(route): get total jokes

This commit is contained in:
Reinaldy Rafli 2021-07-17 21:37:01 +07:00
parent a338f7296e
commit 8ac21a1046
3 changed files with 47 additions and 3 deletions

View File

@ -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,
})
}

View File

@ -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"`
}

View File

@ -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)