jokes-bapak2/api/app/v1/handler/joke_update.go

63 lines
1.3 KiB
Go
Raw Normal View History

2021-07-09 06:11:11 +00:00
package handler
2021-07-09 12:13:19 +00:00
import (
"context"
"jokes-bapak2-api/app/v1/core"
2021-07-14 18:17:01 +00:00
"jokes-bapak2-api/app/v1/models"
2021-07-09 12:13:19 +00:00
"github.com/Masterminds/squirrel"
"github.com/gofiber/fiber/v2"
)
func UpdateJoke(c *fiber.Ctx) error {
id := c.Params("id")
// Check if the joke exists
sql, args, err := psql.Select("id").From("jokesbapak2").Where(squirrel.Eq{"id": id}).ToSql()
if err != nil {
return err
}
var jokeID string
err = db.QueryRow(context.Background(), sql, args...).Scan(&jokeID)
if err != nil && err != models.ErrNoRows {
2021-07-09 12:13:19 +00:00
return err
}
if jokeID == id {
body := new(models.Joke)
2021-07-09 12:13:19 +00:00
err = c.BodyParser(&body)
if err != nil {
return err
}
2021-07-14 18:17:01 +00:00
sql, args, err = psql.Update("jokesbapak2").Set("link", body.Link).Set("creator", c.Locals("userID")).ToSql()
2021-07-09 12:13:19 +00:00
if err != nil {
return err
}
_, err := db.Query(context.Background(), sql, args...)
if err != nil {
return err
}
2021-07-19 10:21:08 +00:00
err = core.SetAllJSONJoke(db, memory)
if err != nil {
return err
}
2021-07-19 10:21:08 +00:00
err = core.SetTotalJoke(db, memory)
if err != nil {
return err
}
2021-07-09 12:13:19 +00:00
return c.Status(fiber.StatusOK).JSON(models.ResponseJoke{
Message: "specified joke id has been updated",
Link: body.Link,
})
}
return c.Status(fiber.StatusNotAcceptable).JSON(models.Error{
2021-07-09 12:13:19 +00:00
Error: "specified joke id does not exists",
})
}