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

74 lines
1.3 KiB
Go
Raw Normal View History

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