contacts.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package handlers
  2. import (
  3. "github.com/gofiber/fiber/v2"
  4. "notabug.org/alimiracle/my-website-api/models"
  5. "notabug.org/alimiracle/my-website-api/responses"
  6. )
  7. func (self Handler) GetAllContacts(c *fiber.Ctx) error {
  8. var contacts []models.Contact
  9. self.Database.FindAll(&contacts)
  10. return c.Status(fiber.StatusOK).JSON(&contacts)
  11. }
  12. func (self Handler) AddContact(c *fiber.Ctx) error {
  13. body := models.Contact{}
  14. if err := c.BodyParser(&body); err != nil {
  15. return responses.BadRequestResponse(c, err)
  16. }
  17. // insert new db entry
  18. err := self.Database.Create(&body)
  19. if err != nil {
  20. return fiber.NewError(fiber.StatusNotFound, err.Error())
  21. }
  22. return c.Status(fiber.StatusCreated).JSON(&body)
  23. }
  24. func (self Handler) UpdateContact(c *fiber.Ctx) error {
  25. id := c.Params("id")
  26. body := models.Contact{}
  27. if err := c.BodyParser(&body); err != nil {
  28. return responses.BadRequestResponse(c, err)
  29. }
  30. err := self.Database.Update(&body, id)
  31. if err != nil {
  32. return fiber.NewError(fiber.StatusNotFound, err.Error())
  33. }
  34. return c.SendStatus(fiber.StatusOK)
  35. }
  36. func (self Handler) DeleteContact(c *fiber.Ctx) error {
  37. id := c.Params("id")
  38. var contact models.Contact
  39. err := self.Database.Delete(&contact, id)
  40. if err != nil {
  41. return fiber.NewError(fiber.StatusNotFound, err.Error())
  42. }
  43. return c.SendStatus(fiber.StatusOK)
  44. }