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

76 lines
1.3 KiB
Go
Raw Normal View History

package joke
import (
2021-09-27 10:10:19 +00:00
"jokes-bapak2-api/app/core"
"strconv"
"github.com/Masterminds/squirrel"
"github.com/gofiber/fiber/v2"
)
func (d *Dependencies) DeleteJoke(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()
id, err := strconv.Atoi(c.Params("id"))
if err != nil {
return err
}
// Check if the joke exists
sql, args, err := d.Query.
2021-08-04 10:14:33 +00:00
Select("id").
From("jokesbapak2").
Where(squirrel.Eq{"id": id}).
ToSql()
if err != nil {
return err
}
var jokeID int
2021-09-27 10:10:19 +00:00
err = conn.QueryRow(*d.Context, sql, args...).Scan(&jokeID)
if err != nil {
return err
}
if jokeID == id {
sql, args, err = d.Query.
2021-08-04 10:14:33 +00:00
Delete("jokesbapak2").
Where(squirrel.Eq{"id": id}).
ToSql()
if err != nil {
return err
}
2021-09-27 10:10:19 +00:00
r, err := conn.Query(*d.Context, sql, args...)
if err != nil {
return err
}
2021-08-04 05:56:14 +00:00
defer r.Close()
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.StatusOK).
JSON(ResponseJoke{
2021-08-04 10:14:33 +00:00
Message: "specified joke id has been deleted",
})
}
2021-08-04 10:14:33 +00:00
return c.
Status(fiber.StatusNotAcceptable).
JSON(Error{
2021-08-04 10:14:33 +00:00
Error: "specified joke id does not exists",
})
}