added contact suggestion route, code refactor

This commit is contained in:
slawk0
2025-02-06 21:57:44 +01:00
parent 915cc0c830
commit 51b426ba54
6 changed files with 65 additions and 11 deletions

View File

@@ -11,13 +11,13 @@ import (
func CheckUserExists(db *sql.DB, username string) (bool, error) {
query := `SELECT COUNT(1) FROM accounts WHERE username = $1`
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)
var count int
err := db.QueryRow(query, username).Scan(&count)
if err != nil {
return false, helpers.NewError(helpers.ErrInternal, "Failed to check user existence", err)
}
return exist, nil
return count > 0, nil
}
func InsertUser(db *sql.DB, username string, passwordHash string) (string, error) {

View File

@@ -7,6 +7,7 @@ import (
"github.com/google/uuid"
"relay-server/helpers"
"relay-server/model"
"strings"
)
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) error {
@@ -317,3 +318,31 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
return contacts, nil
}
func ContactSuggestion(db *sql.DB, contactUsername string) ([]string, error) {
query := `
SELECT username FROM accounts
WHERE LOWER(username) LIKE $1
LIMIT 5;
`
rows, err := db.Query(query, "%"+strings.ToLower(contactUsername)+"%")
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, helpers.NewError(helpers.ErrInternal, "Failed to get contact suggestions", err)
}
var suggestions []string
for rows.Next() {
var suggestion string
err := rows.Scan(&suggestion)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
}
suggestions = append(suggestions, suggestion)
}
if err = rows.Err(); err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "Error processing suggestions", err)
}
return suggestions, nil
}