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-08-03 18:14:32 +00:00
|
|
|
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
)
|
|
|
|
|
2021-09-26 19:13:38 +00:00
|
|
|
func (d *Dependencies) AddNewJoke(c *fiber.Ctx) error {
|
2021-10-18 08:31:17 +00:00
|
|
|
var body schema.Joke
|
|
|
|
err := c.BodyParser(&body)
|
2021-08-03 18:14:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check link validity
|
2021-10-18 08:31:17 +00:00
|
|
|
valid, err := validator.CheckImageValidity(d.HTTP, body.Link)
|
2021-08-03 18:14:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !valid {
|
2021-08-04 10:14:33 +00:00
|
|
|
return c.
|
|
|
|
Status(fiber.StatusBadRequest).
|
2021-09-26 19:13:38 +00:00
|
|
|
JSON(Error{
|
2021-08-04 10:14:33 +00:00
|
|
|
Error: "URL provided is not a valid image",
|
|
|
|
})
|
2021-08-03 18:14:32 +00:00
|
|
|
}
|
2021-10-18 08:31:17 +00:00
|
|
|
|
|
|
|
validateLink, err := validator.LinkAlreadyExists(d.DB, c.Context(), body.Link)
|
2021-09-27 13:02:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-09-28 04:29:54 +00:00
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
if !validateLink {
|
2021-09-27 13:02:58 +00:00
|
|
|
return c.Status(fiber.StatusConflict).JSON(Error{
|
|
|
|
Error: "Given link is already on the jokesbapak2 database",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
err = core.InsertJokeIntoDB(
|
|
|
|
d.DB,
|
|
|
|
c.Context(),
|
|
|
|
schema.Joke{
|
|
|
|
Link: body.Link,
|
|
|
|
Creator: c.Locals("userID").(int),
|
|
|
|
},
|
|
|
|
)
|
2021-08-03 18:14:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
err = core.SetAllJSONJoke(d.DB, c.Context(), d.Memory)
|
2021-08-03 18:14:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
err = core.SetTotalJoke(d.DB, c.Context(), d.Memory)
|
2021-08-03 18:14:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-04 10:14:33 +00:00
|
|
|
return c.
|
|
|
|
Status(fiber.StatusCreated).
|
2021-09-26 19:13:38 +00:00
|
|
|
JSON(ResponseJoke{
|
2021-08-04 10:14:33 +00:00
|
|
|
Link: body.Link,
|
|
|
|
})
|
2021-08-03 18:14:32 +00:00
|
|
|
}
|