Files
relay-server/handlers/contacts.go

100 lines
2.5 KiB
Go

package handlers
import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"relay-server/database"
"relay-server/helpers"
)
func DeleteContact(c *fiber.Ctx) error {
type params struct {
ContactID uuid.UUID `params:"contact_id"`
ConversationID uuid.UUID `params:"conversation_id"`
}
p := new(params)
if err := c.ParamsParser(p); err != nil {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid params", err)
}
if p.ContactID == uuid.Nil {
return helpers.NewError(helpers.ErrInvalidInput, "contact ID is empty", nil)
}
if p.ConversationID == uuid.Nil {
return helpers.NewError(helpers.ErrInvalidInput, "conversation ID is empty", nil)
}
msg, err := database.DeleteContact(database.DB, p.ContactID, p.ConversationID)
if err != nil {
return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err)
}
if msg != "" {
return helpers.NewError(helpers.ErrInvalidInput, msg, nil)
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Contact deleted"})
}
func InsertContact(c *fiber.Ctx) error {
type params struct {
ContactUsername string `params:"contact_username"`
}
userIDVal := c.Locals("userID")
userIDStr, ok := userIDVal.(string)
if !ok {
return helpers.NewError(helpers.ErrInternal, "Internal server error", nil)
}
userID, err := uuid.Parse(userIDStr)
if err != nil {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid user ID format", err)
}
p := new(params)
if err := c.ParamsParser(p); err != nil {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid params", err)
}
if p.ContactUsername == "" {
return helpers.NewError(helpers.ErrInvalidInput, "contact username is empty", nil)
}
if !helpers.IsValidUsername(p.ContactUsername) {
return helpers.NewError(helpers.ErrInvalidInput, "username is invalid", nil)
}
contactID, err := database.GetUserID(database.DB, p.ContactUsername)
if err != nil {
return err
}
newContacts, err := database.InsertContact(database.DB, userID, contactID, p.ContactUsername)
if err != nil {
return err
}
return c.Status(fiber.StatusOK).JSON(newContacts)
}
func GetContacts(c *fiber.Ctx) error {
userIDVal := c.Locals("userID")
userIDStr, ok := userIDVal.(string)
if !ok {
return helpers.NewError(helpers.ErrInternal, "Invalid user session", nil)
}
userID, err := uuid.Parse(userIDStr)
if err != nil {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid user ID format", err)
}
contacts, err := database.GetContacts(database.DB, userID)
if err != nil {
return err
}
return c.Status(fiber.StatusOK).JSON(contacts)
}