add client adding logic

This commit is contained in:
gitGnome
2026-03-25 13:46:53 +01:00
parent defed9c268
commit ca0b85cdb7
4 changed files with 48 additions and 2 deletions
+22
View File
@@ -2,7 +2,9 @@ package main
import ( import (
"context" "context"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
) )
@@ -121,3 +123,23 @@ func DbSetGroupById(ctx context.Context, group *Group) error {
} }
return rows.Err() return rows.Err()
} }
func DbAddClientsToGroup(ctx context.Context, groupId uint32, clientIds []uint32) error {
batch := &pgx.Batch{}
now := time.Now()
for _, cid := range clientIds {
batch.Queue(`
INSERT INTO chat_group_members (group_id, user_id, joined_at)
VALUES ($1, $2, $3)
ON CONFLICT DO NOTHING
`, groupId, cid, now)
}
br := dbConn.SendBatch(ctx, batch)
defer br.Close()
for range clientIds {
if _, err := br.Exec(); err != nil {
return err
}
}
return nil
}
BIN
View File
Binary file not shown.
+5
View File
@@ -8,6 +8,11 @@ require (
golang.org/x/crypto v0.49.0 golang.org/x/crypto v0.49.0
) )
require (
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.20.0 // indirect
)
require ( require (
github.com/golang-jwt/jwt/v5 v5.3.1 github.com/golang-jwt/jwt/v5 v5.3.1
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
+21 -2
View File
@@ -202,6 +202,7 @@ func HttpHandleGroupAddClient(response http.ResponseWriter, request *http.Reques
ctx := request.Context() ctx := request.Context()
var group Group var group Group
group.Id = affectedGroupId
groupPtr, err := CacheGetGroup(affectedGroupId) groupPtr, err := CacheGetGroup(affectedGroupId)
if err == nil { if err == nil {
group = *groupPtr group = *groupPtr
@@ -225,10 +226,28 @@ func HttpHandleGroupAddClient(response http.ResponseWriter, request *http.Reques
return return
} }
usersToAdd := strings.SplitN(usersToAddString, ",", remainingUsersCount+1) userIdStrings := strings.SplitN(usersToAddString, ",", remainingUsersCount+1)
if len(usersToAdd) == 0 { if len(userIdStrings) == 0 {
http.Error(response, "no users to add", http.StatusBadRequest) http.Error(response, "no users to add", http.StatusBadRequest)
return return
} }
clientIds := make([]uint32, 0, len(userIdStrings))
for _, s := range userIdStrings {
id, err := ConvertStringUint32(strings.TrimSpace(s))
if err != nil {
continue
}
clientIds = append(clientIds, id)
}
if len(clientIds) == 0 {
http.Error(response, "no valid users", http.StatusBadRequest)
return
}
err = DbAddClientsToGroup(ctx, group.Id, clientIds)
if err != nil {
http.Error(response, "internal server error", http.StatusInternalServerError)
return
}
} }