2021-08-03 18:14:32 +00:00
|
|
|
package joke
|
|
|
|
|
|
|
|
import (
|
2021-10-30 03:24:53 +00:00
|
|
|
core "jokes-bapak2-api/core/joke"
|
|
|
|
"jokes-bapak2-api/core/schema"
|
|
|
|
"jokes-bapak2-api/core/validator"
|
2021-11-06 17:45:18 +00:00
|
|
|
"strconv"
|
2021-08-03 18:14:32 +00:00
|
|
|
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
)
|
|
|
|
|
2021-09-26 19:13:38 +00:00
|
|
|
func (d *Dependencies) UpdateJoke(c *fiber.Ctx) error {
|
2021-10-18 08:31:17 +00:00
|
|
|
id := c.Params("id")
|
|
|
|
// Check if the joke exists
|
|
|
|
|
|
|
|
jokeExists, err := core.CheckJokeExists(d.DB, c.Context(), id)
|
2021-09-27 10:10:19 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
if !jokeExists {
|
|
|
|
return c.
|
|
|
|
Status(fiber.StatusNotAcceptable).
|
|
|
|
JSON(Error{
|
|
|
|
Error: "specified joke id does not exists",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
body := new(schema.Joke)
|
|
|
|
err = c.BodyParser(&body)
|
2021-08-03 18:14:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
// Check link validity
|
|
|
|
valid, err := validator.CheckImageValidity(d.HTTP, body.Link)
|
|
|
|
if err != nil {
|
2021-08-03 18:14:32 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
if !valid {
|
|
|
|
return c.
|
|
|
|
Status(fiber.StatusBadRequest).
|
|
|
|
JSON(Error{
|
|
|
|
Error: "URL provided is not a valid image",
|
|
|
|
})
|
|
|
|
}
|
2021-08-03 18:14:32 +00:00
|
|
|
|
2021-11-06 17:45:18 +00:00
|
|
|
newID, err := strconv.Atoi(id)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
newCreator, err := strconv.Atoi(c.Locals("userID").(string))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
updatedJoke := schema.Joke{
|
|
|
|
Link: body.Link,
|
|
|
|
Creator: newCreator,
|
|
|
|
ID: newID,
|
|
|
|
}
|
|
|
|
|
|
|
|
err = core.UpdateJoke(d.DB, c.Context(), updatedJoke)
|
2021-10-18 08:31:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-08-04 05:56:14 +00:00
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
err = core.SetAllJSONJoke(d.DB, c.Context(), d.Memory)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-08-03 18:14:32 +00:00
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
err = core.SetTotalJoke(d.DB, c.Context(), d.Memory)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-08-03 18:14:32 +00:00
|
|
|
}
|
|
|
|
|
2021-08-04 10:14:33 +00:00
|
|
|
return c.
|
2021-10-18 08:31:17 +00:00
|
|
|
Status(fiber.StatusOK).
|
|
|
|
JSON(ResponseJoke{
|
|
|
|
Message: "specified joke id has been updated",
|
|
|
|
Link: body.Link,
|
2021-08-04 10:14:33 +00:00
|
|
|
})
|
2021-08-03 18:14:32 +00:00
|
|
|
}
|