code refactor, added contact post route

This commit is contained in:
slawk0
2025-02-04 19:53:43 +01:00
parent cd83870ab4
commit ca2debca31
9 changed files with 319 additions and 52 deletions

View File

@@ -3,6 +3,7 @@ package database
import (
"database/sql"
"fmt"
"github.com/google/uuid"
_ "github.com/lib/pq"
"log"
)
@@ -34,7 +35,7 @@ func CheckUserExists(db *sql.DB, username string) (bool, error) {
err := db.QueryRow(query, username).Scan(&count)
if err != nil {
return false, fmt.Errorf("error checking username exists: %v", err)
return false, fmt.Errorf("error checking username exists: %w", err)
}
return count > 0, err
@@ -47,15 +48,15 @@ func InsertUser(db *sql.DB, username string, passwordHash string) (string, error
RETURNING user_id;
`
var userId string
err := db.QueryRow(query, username, passwordHash).Scan(&userId)
var userID string
err := db.QueryRow(query, username, passwordHash).Scan(&userID)
if err != nil {
return "", fmt.Errorf("error inserting user: %v", err)
return "", fmt.Errorf("error inserting user: %w", err)
}
log.Printf("Inserted user: %v", username)
fmt.Printf("Inserted user: %w", username)
return userId, err
return userID, err
}
func GetPasswordHash(db *sql.DB, username string) (string, error) {
@@ -67,24 +68,22 @@ func GetPasswordHash(db *sql.DB, username string) (string, error) {
var passwordHash string
err := db.QueryRow(query, username).Scan(&passwordHash)
if err != nil {
fmt.Printf("error getting password hash: %v\n", err)
return "", fmt.Errorf("error getting password hash: %v", err)
return "", fmt.Errorf("error getting password hash: %w", err)
}
return passwordHash, err
}
func GetUserId(db *sql.DB, username string) (string, error) {
func GetUserID(db *sql.DB, username string) (uuid.UUID, error) {
query := `
SELECT user_id FROM Accounts
WHERE LOWER(username) = $1;
WHERE LOWER(username) = LOWER($1);
`
var dbUsername string
err := db.QueryRow(query, username).Scan(&dbUsername)
var userID uuid.UUID
err := db.QueryRow(query, username).Scan(&userID)
if err != nil {
fmt.Printf("Error getting password: %v\n", err)
return "", fmt.Errorf("error getting user id: %v", err)
return uuid.Nil, fmt.Errorf("error getting user id: %w", err)
}
return dbUsername, err
return userID, nil
}

View File

@@ -5,7 +5,7 @@ import (
"errors"
"fmt"
"github.com/google/uuid"
"log"
"relay-server/model"
)
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (string, error) {
@@ -58,8 +58,6 @@ func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (stri
if rowsAffected == 0 {
return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID)
}
log.Printf("Successfully removed user %s from group %s", userID, conversationID)
} else {
// Handle direct conversation
res, err := db.Exec(
@@ -68,21 +66,198 @@ func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (stri
conversationID,
)
if err != nil {
log.Printf("Error deleting contact: %v", err)
return "", fmt.Errorf("error deleting contact: %w", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
log.Printf("Error checking contact deletion: %v", err)
return "", fmt.Errorf("error checking contact deletion: %w", err)
}
if rowsAffected == 0 {
return fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil
}
log.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID)
fmt.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID)
}
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(findSelfConversationQuery, userID).Scan(&conversationID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, fmt.Errorf("error finding 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)
if err != nil {
return nil, fmt.Errorf("error creating conversation for self-contact: %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)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, 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, 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, fmt.Errorf("error creating membership: %w", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("error checking membership creation: %w", err)
}
if rowsAffected == 0 {
return nil, fmt.Errorf("error creating membership %w", err)
}
}
}
}
insertedContact, err := InsertContactByID(db, contactID, conversationID)
if err != nil || insertedContact.UserID == uuid.Nil {
return nil, fmt.Errorf("error inserting contact by id: %w", err)
}
latestMessage, err := GetLatestMessage(db, conversationID)
if err != nil {
return nil, fmt.Errorf("error getting latest message: %w", err)
}
contact = model.Contact{
ID: insertedContact.ID,
ConversationID: insertedContact.ConversationID,
UserID: insertedContact.UserID,
Username: contactUsername,
Type: "direct",
LastMessageID: latestMessage.LastMessageID,
LastMessage: latestMessage.LastMessage,
LastMessageTime: latestMessage.LastMessageTime,
LastMessageSender: latestMessage.LastMessageSender,
}
return &contact, nil
}
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)
if err == nil {
return nil, fmt.Errorf("contact already exists")
} else if !errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("error checking contact existence: %w", err)
}
insertQuery := `
INSERT INTO Contacts (user_id, conversation_id)
VALUES($1, $2)
RETURNING contact_id, conversation_id, user_id
`
err = db.QueryRow(insertQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err != nil {
return nil, fmt.Errorf("error inserting contact: %w", err)
}
fmt.Printf("Successfully inserted contact by id: %v", conversationID)
return &contact, nil
}
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(query, conversationId).Scan(&latestMessage.LastMessageID, &latestMessage.LastMessage, &latestMessage.LastMessageTime, &latestMessage.LastMessageSender)
if err != nil {
return nil, fmt.Errorf("error getting latest message: %w", err)
}
return &latestMessage, nil
}