implemented new error handler, added getContacts route
This commit is contained in:
@@ -2,88 +2,71 @@ package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
_ "github.com/lib/pq"
|
||||
"log"
|
||||
"relay-server/helpers"
|
||||
)
|
||||
|
||||
func GetUsers(db *sql.DB) ([]string, error) {
|
||||
query := `SELECT username FROM accounts;`
|
||||
|
||||
rows, err := db.Query(query)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var users []string
|
||||
for rows.Next() {
|
||||
var user string
|
||||
if err := rows.Scan(&user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, err
|
||||
}
|
||||
|
||||
func CheckUserExists(db *sql.DB, username string) (bool, error) {
|
||||
query := `SELECT COUNT(1) FROM accounts WHERE username= $1`
|
||||
query := `SELECT COUNT(1) FROM accounts WHERE username = $1`
|
||||
|
||||
var count int
|
||||
|
||||
err := db.QueryRow(query, username).Scan(&count)
|
||||
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error checking username exists: %w", err)
|
||||
var exist bool
|
||||
err := db.QueryRow(query, username).Scan(&exist)
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return false, helpers.NewError(helpers.ErrInternal, "Failed to check username", err)
|
||||
}
|
||||
|
||||
return count > 0, err
|
||||
return exist, nil
|
||||
}
|
||||
|
||||
func InsertUser(db *sql.DB, username string, passwordHash string) (string, error) {
|
||||
query := `
|
||||
INSERT INTO Accounts (username, password_hash)
|
||||
VALUES ($1, $2)
|
||||
RETURNING user_id;
|
||||
`
|
||||
INSERT INTO Accounts (username, password_hash)
|
||||
VALUES ($1, $2)
|
||||
RETURNING user_id;
|
||||
`
|
||||
|
||||
var userID string
|
||||
err := db.QueryRow(query, username, passwordHash).Scan(&userID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error inserting user: %w", err)
|
||||
return "", helpers.NewError(helpers.ErrInternal, "Failed to create user", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Inserted user: %w", username)
|
||||
|
||||
return userID, err
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func GetPasswordHash(db *sql.DB, username string) (string, error) {
|
||||
query := `
|
||||
SELECT password_hash FROM Accounts
|
||||
WHERE LOWER(username) = LOWER($1);
|
||||
`
|
||||
SELECT password_hash FROM Accounts
|
||||
WHERE LOWER(username) = LOWER($1);
|
||||
`
|
||||
|
||||
var passwordHash string
|
||||
err := db.QueryRow(query, username).Scan(&passwordHash)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error getting password hash: %w", err)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", helpers.NewError(helpers.ErrNotFound, "User not found", nil)
|
||||
}
|
||||
return "", helpers.NewError(helpers.ErrInternal, "Failed to get user credentials", err)
|
||||
}
|
||||
|
||||
return passwordHash, err
|
||||
return passwordHash, nil
|
||||
}
|
||||
|
||||
func GetUserID(db *sql.DB, username string) (uuid.UUID, error) {
|
||||
query := `
|
||||
SELECT user_id FROM Accounts
|
||||
WHERE LOWER(username) = LOWER($1);
|
||||
`
|
||||
SELECT user_id FROM Accounts
|
||||
WHERE LOWER(username) = LOWER($1);
|
||||
`
|
||||
|
||||
var userID uuid.UUID
|
||||
err := db.QueryRow(query, username).Scan(&userID)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("error getting user id: %w", err)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return uuid.Nil, helpers.NewError(helpers.ErrNotFound, "User not found", nil)
|
||||
}
|
||||
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to get user ID", err)
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"log"
|
||||
"relay-server/helpers"
|
||||
"relay-server/model"
|
||||
)
|
||||
|
||||
@@ -108,7 +110,7 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
conversationID = uuid.Nil
|
||||
}
|
||||
return nil, fmt.Errorf("error finding existing conversation: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
|
||||
}
|
||||
|
||||
// if conversation for themselves don't exist
|
||||
@@ -120,7 +122,7 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
|
||||
`
|
||||
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating conversation for self-contact: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "Internal server error", fmt.Errorf("error creating conversation for self-contact: %w", err))
|
||||
}
|
||||
|
||||
createMembershipQuery := `
|
||||
@@ -150,7 +152,7 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
conversationID = uuid.Nil
|
||||
}
|
||||
return nil, fmt.Errorf("error finding existing conversation: %w", err)
|
||||
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
|
||||
@@ -161,7 +163,7 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
|
||||
`
|
||||
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating conversation: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating conversation: %w", err))
|
||||
}
|
||||
|
||||
createMembershipQuery := `
|
||||
@@ -172,14 +174,14 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
|
||||
|
||||
res, err := db.Exec(createMembershipQuery, conversationID, userID, contactID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating membership: %w", err)
|
||||
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, fmt.Errorf("error checking membership creation: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking membership creation: %w", err))
|
||||
}
|
||||
if rowsAffected == 0 {
|
||||
return nil, fmt.Errorf("error creating membership %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership %w", err))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,12 +189,12 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
|
||||
}
|
||||
insertedContact, err := InsertContactByID(db, contactID, conversationID)
|
||||
if err != nil || insertedContact.UserID == uuid.Nil {
|
||||
return nil, fmt.Errorf("error inserting contact by id: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
|
||||
}
|
||||
|
||||
latestMessage, err := GetLatestMessage(db, conversationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error getting latest message: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
|
||||
}
|
||||
|
||||
contact = model.Contact{
|
||||
@@ -219,9 +221,9 @@ func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (
|
||||
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")
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("contact already exists"))
|
||||
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, fmt.Errorf("error checking contact existence: %w", err)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking contact existence: %w", err))
|
||||
}
|
||||
|
||||
insertQuery := `
|
||||
@@ -232,7 +234,7 @@ func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (
|
||||
|
||||
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)
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error inserting contact: %w", err))
|
||||
}
|
||||
fmt.Printf("Successfully inserted contact by id: %v", conversationID)
|
||||
|
||||
@@ -257,7 +259,90 @@ func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, err
|
||||
|
||||
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 nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err))
|
||||
}
|
||||
return &latestMessage, nil
|
||||
}
|
||||
|
||||
func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
|
||||
contactsQuery := `
|
||||
WITH DirectContacts AS (
|
||||
SELECT DISTINCT ON (c.conversation_id)
|
||||
c.contact_id AS id,
|
||||
a.user_id AS user_id,
|
||||
a.username AS username,
|
||||
conv.last_active,
|
||||
c.conversation_id,
|
||||
conv.conversation_type AS type,
|
||||
requesting_member.last_read_message_id
|
||||
FROM Contacts c
|
||||
JOIN Conversations conv ON c.conversation_id = conv.conversation_id
|
||||
JOIN Memberships requesting_member
|
||||
ON requesting_member.conversation_id = conv.conversation_id
|
||||
AND requesting_member.user_id = $1
|
||||
JOIN Memberships other_member
|
||||
ON other_member.conversation_id = conv.conversation_id
|
||||
JOIN Accounts a ON a.user_id = other_member.user_id
|
||||
WHERE c.user_id = $1
|
||||
AND conv.conversation_type = 'direct'
|
||||
AND (
|
||||
a.user_id != $1
|
||||
OR (SELECT COUNT(*) FROM Memberships WHERE conversation_id = c.conversation_id) = 1
|
||||
)
|
||||
),
|
||||
GroupContacts AS (
|
||||
SELECT DISTINCT ON (c.conversation_id)
|
||||
c.contact_id AS id,
|
||||
NULL::uuid AS user_id,
|
||||
conv.name AS username,
|
||||
conv.last_active,
|
||||
c.conversation_id,
|
||||
conv.conversation_type AS type,
|
||||
m.last_read_message_id
|
||||
FROM Contacts c
|
||||
JOIN Conversations conv ON c.conversation_id = conv.conversation_id
|
||||
JOIN Memberships m
|
||||
ON m.conversation_id = conv.conversation_id
|
||||
AND m.user_id = $1
|
||||
WHERE c.user_id = $1
|
||||
AND conv.conversation_type = 'group'
|
||||
)
|
||||
SELECT * FROM DirectContacts
|
||||
UNION ALL
|
||||
SELECT * FROM GroupContacts
|
||||
ORDER BY last_active DESC NULLS LAST;
|
||||
`
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
var contacts []*model.Contact
|
||||
for rows.Next() {
|
||||
contact := &model.Contact{}
|
||||
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))
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
contact.LastMessageID = latestMessage.LastMessageID
|
||||
contact.LastMessage = latestMessage.LastMessage
|
||||
contact.LastMessageTime = latestMessage.LastMessageTime
|
||||
contact.LastMessageSender = latestMessage.LastMessageSender
|
||||
|
||||
contacts = append(contacts, contact)
|
||||
}
|
||||
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error iterating over contacts: %w", err))
|
||||
}
|
||||
|
||||
return contacts, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user