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

64 lines
1.0 KiB
Go
Raw Normal View History

package joke
import (
"context"
"jokes-bapak2-api/app/v1/core"
"github.com/gofiber/fiber/v2"
)
func (d *Dependencies) AddNewJoke(c *fiber.Ctx) error {
var body core.Joke
err := c.BodyParser(&body)
if err != nil {
return err
}
// Check link validity
valid, err := core.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",
})
}
sql, args, err := d.Query.
2021-08-04 10:14:33 +00:00
Insert("jokesbapak2").
Columns("link", "creator").
Values(body.Link, c.Locals("userID")).
ToSql()
if err != nil {
return err
}
// TODO: Implement solution if the link provided already exists.
r, err := d.DB.Query(context.Background(), sql, args...)
if err != nil {
return err
}
2021-08-04 05:56:14 +00:00
defer r.Close()
err = core.SetAllJSONJoke(d.DB, d.Memory)
if err != nil {
return err
}
err = core.SetTotalJoke(d.DB, 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,
})
}