finished implementing new error handler

This commit is contained in:
slawk0
2025-02-06 21:08:51 +01:00
parent 79357c8ae2
commit 915cc0c830
3 changed files with 210 additions and 235 deletions

View File

@@ -5,13 +5,11 @@ import (
"errors"
"fmt"
"github.com/google/uuid"
"log"
"relay-server/helpers"
"relay-server/model"
)
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (string, error) {
// Check conversation type
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) error {
var conversationType string
err := db.QueryRow(
"SELECT conversation_type FROM Conversations WHERE conversation_id = $1",
@@ -19,185 +17,151 @@ func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (stri
).Scan(&conversationType)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "no conversation found for this id", nil
return helpers.NewError(helpers.ErrNotFound, "no contacts found for this id", fmt.Errorf("no conversation found with id: %s", conversationID))
}
return "", fmt.Errorf("error checking conversation type: %w", err)
return helpers.NewError(helpers.ErrInternal, "Failed to check conversation", err)
}
if conversationType == "group" {
// Delete from Contacts
res, err := db.Exec(
"DELETE FROM Contacts WHERE conversation_id = $1 AND user_id = $2",
conversationID,
userID,
conversationID, userID,
)
if err != nil {
return "", fmt.Errorf("error deleting contact: %w", err)
return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return "", fmt.Errorf("error checking contact deletion: %w", err)
return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to verify contact deletion: %w", err))
}
if rowsAffected == 0 {
return fmt.Sprintf("no matching contact found with conversation id: %s, user id: %s", conversationID, userID), nil
return helpers.NewError(helpers.ErrNotFound, fmt.Sprintf("no matching contact found with conversation id: %s, user id: %s", conversationID, userID), nil)
}
// Delete from Memberships
res, err = db.Exec(
"DELETE FROM Memberships WHERE conversation_id = $1 AND user_id = $2",
conversationID,
userID,
conversationID, userID,
)
if err != nil {
return "", fmt.Errorf("error deleting membership: %w", err)
return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to delete membership: %w", err))
}
rowsAffected, err = res.RowsAffected()
if err != nil {
return "", fmt.Errorf("error checking membership deletion: %w", err)
return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to verify membership deletion: %w", err))
}
if rowsAffected == 0 {
return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID)
return helpers.NewError(helpers.ErrNotFound, "No membership found", err)
}
} else {
// Handle direct conversation
res, err := db.Exec(
"DELETE FROM Contacts WHERE user_id = $1 AND conversation_id = $2",
userID,
conversationID,
userID, conversationID,
)
if err != nil {
return "", fmt.Errorf("error deleting contact: %w", err)
return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return "", fmt.Errorf("error checking contact deletion: %w", err)
return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to verify contact deletion: %w", err))
}
if rowsAffected == 0 {
return fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil
return helpers.NewError(helpers.ErrNotFound, fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil)
}
fmt.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID)
}
return "", nil
return nil
}
func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUsername string) (*model.Contact, error) {
isSelfContact := userID == contactID
var contact model.Contact
var conversationID uuid.UUID
if isSelfContact {
findSelfConversationQuery := `
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m ON c.conversation_id = m.conversation_id
WHERE c.conversation_type = 'direct'
AND m.user_id = $1
AND (
SELECT COUNT(*)
FROM Memberships
WHERE conversation_id = c.conversation_id
) = 1
LIMIT 1;
`
err := db.QueryRow(`
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m ON c.conversation_id = m.conversation_id
WHERE c.conversation_type = 'direct'
AND m.user_id = $1
AND (SELECT COUNT(*) FROM Memberships WHERE conversation_id = c.conversation_id) = 1
LIMIT 1;
`, userID).Scan(&conversationID)
err := db.QueryRow(findSelfConversationQuery, userID).Scan(&conversationID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check existing conversation: %w", err))
}
// if conversation for themselves don't exist
if conversationID == uuid.Nil {
createConversationQuery := `
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
err := db.QueryRow(`
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`).Scan(&conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "Internal server error", fmt.Errorf("error creating conversation for self-contact: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create conversation: %w", err))
}
createMembershipQuery := `
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`
_, err = db.Exec(createMembershipQuery, conversationID, userID)
} else {
// For regular contacts, check if a conversation already exists between the two users
findConversationQuery := `
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m1 ON c.conversation_id = m1.conversation_id
JOIN Memberships m2 ON c.conversation_id = m2.conversation_id
WHERE c.conversation_type = 'direct'
AND (
(m1.user_id = $1 AND m2.user_id = $2)
OR
(m1.user_id = $2 AND m2.user_id = $1)
)
LIMIT 1;
`
err := db.QueryRow(findConversationQuery, userID, contactID).Scan(&conversationID)
_, err = db.Exec(`
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`, conversationID, userID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
}
if conversationID != uuid.Nil {
// Create a new conversation between user and contact
createConversationQuery := `
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating conversation: %w", err))
}
createMembershipQuery := `
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2), ($1, $3)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`
res, err := db.Exec(createMembershipQuery, conversationID, userID, contactID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership: %w", err))
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking membership creation: %w", err))
}
if rowsAffected == 0 {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership %w", err))
}
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create membership: %w", err))
}
}
} else {
err := db.QueryRow(`
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m1 ON c.conversation_id = m1.conversation_id
JOIN Memberships m2 ON c.conversation_id = m2.conversation_id
WHERE c.conversation_type = 'direct'
AND ((m1.user_id = $1 AND m2.user_id = $2) OR (m1.user_id = $2 AND m2.user_id = $1))
LIMIT 1;
`, userID, contactID).Scan(&conversationID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check existing conversation %w", err))
}
if conversationID == uuid.Nil {
err := db.QueryRow(`
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`).Scan(&conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create conversation: %w", err))
}
_, err = db.Exec(`
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2), ($1, $3)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`, conversationID, userID, contactID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create memberships: %w", err))
}
}
}
insertedContact, err := InsertContactByID(db, contactID, conversationID)
if err != nil || insertedContact.UserID == uuid.Nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
if err != nil {
return nil, err
}
latestMessage, err := GetLatestMessage(db, conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
return nil, err
}
contact = model.Contact{
contact := model.Contact{
ID: insertedContact.ID,
ConversationID: insertedContact.ConversationID,
UserID: insertedContact.UserID,
@@ -213,30 +177,29 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (*model.Contact, error) {
// First check if contact already exists
checkQuery := `
SELECT contact_id, conversation_id, user_id
FROM Contacts
WHERE user_id = $1 AND conversation_id = $2
`
var contact model.Contact
err := db.QueryRow(checkQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
err := db.QueryRow(`
SELECT contact_id, conversation_id, user_id
FROM Contacts
WHERE user_id = $1 AND conversation_id = $2
`, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err == nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("contact already exists"))
return nil, helpers.NewError(helpers.ErrInvalidInput, "Contact already exists", nil)
} else if !errors.Is(err, sql.ErrNoRows) {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking contact existence: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check contact existence: %w", err))
}
insertQuery := `
INSERT INTO Contacts (user_id, conversation_id)
VALUES($1, $2)
RETURNING contact_id, conversation_id, user_id
`
// Insert new contact
err = db.QueryRow(`
INSERT INTO Contacts (user_id, conversation_id)
VALUES($1, $2)
RETURNING contact_id, conversation_id, user_id
`, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
err = db.QueryRow(insertQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error inserting contact: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "Failed to create contact", err)
}
fmt.Printf("Successfully inserted contact by id: %v", conversationID)
return &contact, nil
}
@@ -244,23 +207,31 @@ func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (
func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, error) {
var latestMessage model.Contact
query := `
SELECT DISTINCT ON (m.conversation_id)
m.message_id AS last_message_id,
m.content AS last_message,
m.sent_at AS last_message_time,
a.username AS last_message_sender
FROM Messages m
JOIN Accounts a ON m.user_id = a.user_id
WHERE m.conversation_id = $1
ORDER BY m.conversation_id, m.sent_at DESC
LIMIT 1;
`
err := db.QueryRow(`
SELECT DISTINCT ON (m.conversation_id)
m.message_id AS last_message_id,
m.content AS last_message,
m.sent_at AS last_message_time,
a.username AS last_message_sender
FROM Messages m
JOIN Accounts a ON m.user_id = a.user_id
WHERE m.conversation_id = $1
ORDER BY m.conversation_id, m.sent_at DESC
LIMIT 1;
`, conversationId).Scan(
&latestMessage.LastMessageID,
&latestMessage.LastMessage,
&latestMessage.LastMessageTime,
&latestMessage.LastMessageSender,
)
err := db.QueryRow(query, conversationId).Scan(&latestMessage.LastMessageID, &latestMessage.LastMessage, &latestMessage.LastMessageTime, &latestMessage.LastMessageSender)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err))
if errors.Is(err, sql.ErrNoRows) {
return &model.Contact{}, nil // Return empty contact if no messages
}
return nil, helpers.NewError(helpers.ErrInternal, "Failed to get latest message", err)
}
return &latestMessage, nil
}
@@ -315,21 +286,21 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
rows, err := db.Query(contactsQuery, userID)
if err != nil {
log.Println("Failed to get contacts:", err)
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting contacts: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "Failed to get contacts", err)
}
var contacts []*model.Contact
for rows.Next() {
contact := &model.Contact{}
err := rows.Scan(&contact.ID, &contact.UserID, &contact.Username, &contact.ConversationID, &contact.Type)
err := rows.Scan(&contact.ID, &contact.UserID, &contact.Username,
&contact.ConversationID, &contact.Type)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error scanning contact: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
}
latestMessage, err := GetLatestMessage(db, contact.ConversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err))
return nil, err
}
contact.LastMessageID = latestMessage.LastMessageID
@@ -341,7 +312,7 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
}
if err = rows.Err(); err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error iterating over contacts: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "Failed to process contacts", err)
}
return contacts, nil