jokes-bapak2/api/app/handler/joke/joke_add.go

70 lines
1.2 KiB
Go
Raw Normal View History

package joke
import (
core "jokes-bapak2-api/app/core/joke"
"jokes-bapak2-api/app/core/schema"
"jokes-bapak2-api/app/core/validator"
"github.com/gofiber/fiber/v2"
)
func (d *Dependencies) AddNewJoke(c *fiber.Ctx) error {
var body schema.Joke
err := c.BodyParser(&body)
if err != nil {
return err
}
// Check link validity
valid, err := validator.CheckImageValidity(d.HTTP, body.Link)
if err != nil {
return err
}
if !valid {
2021-08-04 10:14:33 +00:00
return c.
Status(fiber.StatusBadRequest).
JSON(Error{
2021-08-04 10:14:33 +00:00
Error: "URL provided is not a valid image",
})
}
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
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",
})
}
err = core.InsertJokeIntoDB(
d.DB,
c.Context(),
schema.Joke{
Link: body.Link,
Creator: c.Locals("userID").(int),
},
)
if err != nil {
return err
}
err = core.SetAllJSONJoke(d.DB, c.Context(), d.Memory)
if err != nil {
return err
}
err = core.SetTotalJoke(d.DB, c.Context(), d.Memory)
if err != nil {
return err
}
2021-08-04 10:14:33 +00:00
return c.
Status(fiber.StatusCreated).
JSON(ResponseJoke{
2021-08-04 10:14:33 +00:00
Link: body.Link,
})
}