94 lines
2.6 KiB
Go
94 lines
2.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/google/uuid"
|
|
"log"
|
|
"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 c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid params"})
|
|
}
|
|
|
|
db := database.DB
|
|
|
|
if p.ContactID == uuid.Nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "contact_id is empty"})
|
|
}
|
|
if p.ConversationID == uuid.Nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "conversation_id is empty"})
|
|
}
|
|
|
|
msg, err := database.DeleteContact(db, p.ContactID, p.ConversationID)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Internal server error"})
|
|
}
|
|
if msg != "" {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": msg})
|
|
}
|
|
fmt.Println("Contact deleted")
|
|
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Contact deleted"})
|
|
}
|
|
|
|
func InsertContact(c *fiber.Ctx) error {
|
|
userID, err := uuid.Parse(c.Locals("userID").(string))
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Internal server error"})
|
|
}
|
|
type params struct {
|
|
ContactUsername string `params:"contact_username"`
|
|
}
|
|
|
|
p := new(params)
|
|
|
|
if err := c.ParamsParser(p); err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid params"})
|
|
}
|
|
|
|
db := database.DB
|
|
|
|
if p.ContactUsername == "" {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "contact_username is empty"})
|
|
}
|
|
|
|
if !helpers.IsValidUsername(p.ContactUsername) {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "username is invalid"})
|
|
}
|
|
|
|
contactID, err := database.GetUserID(db, p.ContactUsername)
|
|
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "user does not exist"})
|
|
}
|
|
log.Println(err)
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Internal server error"})
|
|
}
|
|
|
|
newContacts, err := database.InsertContact(db, userID, contactID, p.ContactUsername)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Internal server error"})
|
|
}
|
|
|
|
log.Println("Contact added")
|
|
return c.Status(fiber.StatusOK).JSON(newContacts)
|
|
|
|
}
|