added create group route

This commit is contained in:
slawk0
2025-02-08 00:13:31 +01:00
parent 68873dc44c
commit bb67001839
4 changed files with 94 additions and 0 deletions

53
database/groups.go Normal file
View File

@@ -0,0 +1,53 @@
package database
import (
"database/sql"
"fmt"
"github.com/google/uuid"
"relay-server/helpers"
)
func CreateGroup(db *sql.DB, groupName string, userID uuid.UUID) (uuid.UUID, error) {
createConversationQuery := `
INSERT INTO Conversations (conversation_type, name)
VALUES ('group', $1)
RETURNING conversation_id AS group_id;
`
insertGroupAdminQuery := `
INSERT INTO GroupAdmins (conversation_id, user_id, granted_by, is_owner)
VALUES ($1, $2, $3, true)
RETURNING granted_at;
`
addMemberToGroupQuery := `
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
RETURNING user_id;
`
var groupID uuid.UUID
err := db.QueryRow(createConversationQuery, groupName).Scan(&groupID)
if err != nil {
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to create group", fmt.Errorf("failed to create group: %w", err))
}
var grantedAt string
err = db.QueryRow(insertGroupAdminQuery, groupID, userID, userID).Scan(&grantedAt)
if err != nil {
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to create group", fmt.Errorf("failed to insert group admin: %w", err))
}
var memberID uuid.UUID
err = db.QueryRow(addMemberToGroupQuery, groupID, userID).Scan(&memberID)
if err != nil {
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to create group", fmt.Errorf("failed to add member to group: %w", err))
}
_, err = InsertContactByID(db, userID, groupID)
if err != nil {
return groupID, helpers.NewError(helpers.ErrInternal, "Failed to create group contact", fmt.Errorf("failed to insert group contact: %w", err))
}
return groupID, nil
}