mirror of
https://github.com/kevin-DL/services.git
synced 2026-01-19 22:15:24 +00:00
multi tenant chats (#79)
This commit is contained in:
@@ -3,11 +3,12 @@ package handler
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/micro/micro/v3/service/auth"
|
||||
"github.com/micro/micro/v3/service/errors"
|
||||
"github.com/micro/micro/v3/service/logger"
|
||||
pb "github.com/micro/services/chats/proto"
|
||||
@@ -16,6 +17,10 @@ import (
|
||||
// Create a chat between two or more users, if a chat already exists for these users, the existing
|
||||
// chat will be returned
|
||||
func (c *Chats) CreateChat(ctx context.Context, req *pb.CreateChatRequest, rsp *pb.CreateChatResponse) error {
|
||||
_, ok := auth.AccountFromContext(ctx)
|
||||
if !ok {
|
||||
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
|
||||
}
|
||||
// validate the request
|
||||
if len(req.UserIds) < 2 {
|
||||
return ErrMissingUserIDs
|
||||
@@ -36,19 +41,25 @@ func (c *Chats) CreateChat(ctx context.Context, req *pb.CreateChatRequest, rsp *
|
||||
UserIDs: string(bytes),
|
||||
}
|
||||
|
||||
db, err := c.GetDBConn(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf("Error connecting to DB: %v", err)
|
||||
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
|
||||
}
|
||||
// write to the database, if we get a unique key error, the chat already exists
|
||||
err = c.DB.Create(&chat).Error
|
||||
err = db.Create(&chat).Error
|
||||
if err == nil {
|
||||
rsp.Chat = chat.Serialize()
|
||||
return nil
|
||||
}
|
||||
if !strings.Contains(err.Error(), "idx_chats_user_ids") {
|
||||
|
||||
if match, _ := regexp.MatchString(`idx_[\S]+_chats_user_ids`, err.Error()); !match {
|
||||
logger.Errorf("Error creating chat: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
|
||||
var existing Chat
|
||||
if err := c.DB.Where(&Chat{UserIDs: chat.UserIDs}).First(&existing).Error; err != nil {
|
||||
if err := db.Where(&Chat{UserIDs: chat.UserIDs}).First(&existing).Error; err != nil {
|
||||
logger.Errorf("Error reading chat: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user