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

98 lines
1.8 KiB
Go
Raw Normal View History

package joke
import (
2021-09-27 10:10:19 +00:00
"jokes-bapak2-api/app/core"
2021-09-27 13:02:58 +00:00
"github.com/Masterminds/squirrel"
"github.com/gofiber/fiber/v2"
2021-09-27 13:02:58 +00:00
"github.com/jackc/pgx/v4"
)
func (d *Dependencies) AddNewJoke(c *fiber.Ctx) error {
2021-09-27 10:10:19 +00:00
conn, err := d.DB.Acquire(*d.Context)
if err != nil {
return err
}
defer conn.Release()
tx, err := conn.Begin(*d.Context)
if err != nil {
return err
}
defer tx.Rollback(*d.Context)
var body core.Joke
2021-09-27 10:10:19 +00:00
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",
})
}
2021-09-27 13:02:58 +00:00
// Validate if link already exists
sql, args, err := d.Query.
2021-09-27 13:02:58 +00:00
Select("link").
From("jokesbapak2").
Where(squirrel.Eq{"link": body.Link}).
ToSql()
if err != nil {
return err
}
2021-09-28 04:29:39 +00:00
var validateLink string
err = conn.QueryRow(*d.Context, sql, args...).Scan(&validateLink)
2021-09-27 13:02:58 +00:00
if err != nil && err != pgx.ErrNoRows {
return err
}
2021-09-28 04:29:54 +00:00
2021-09-28 04:29:39 +00:00
if err == nil && 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",
})
}
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
}
2021-09-27 10:10:19 +00:00
_, err = tx.Exec(*d.Context, sql, args...)
if err != nil {
return err
}
2021-09-27 10:10:19 +00:00
err = tx.Commit(*d.Context)
if err != nil {
return err
}
2021-08-04 05:56:14 +00:00
2021-09-27 10:10:19 +00:00
err = core.SetAllJSONJoke(d.DB, d.Memory, d.Context)
if err != nil {
return err
}
2021-09-27 10:10:19 +00:00
err = core.SetTotalJoke(d.DB, d.Memory, d.Context)
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,
})
}