mirror of
https://github.com/kevin-DL/services.git
synced 2026-01-12 03:05:14 +00:00
Add idempotent_id to chat and threads services (#64)
* Add idempotent_id to chat and threads services * Rename
This commit is contained in:
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/micro/micro/v3/service/errors"
|
||||
@@ -23,31 +24,40 @@ func (s *Threads) CreateMessage(ctx context.Context, req *pb.CreateMessageReques
|
||||
return ErrMissingText
|
||||
}
|
||||
|
||||
return s.DB.Transaction(func(tx *gorm.DB) error {
|
||||
// lookup the conversation
|
||||
var conv Conversation
|
||||
if err := tx.Where(&Conversation{ID: req.ConversationId}).First(&conv).Error; err == gorm.ErrRecordNotFound {
|
||||
return ErrNotFound
|
||||
} else if err != nil {
|
||||
logger.Errorf("Error reading conversation: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
// lookup the conversation
|
||||
var conv Conversation
|
||||
if err := s.DB.Where(&Conversation{ID: req.ConversationId}).First(&conv).Error; err == gorm.ErrRecordNotFound {
|
||||
return ErrNotFound
|
||||
} else if err != nil {
|
||||
logger.Errorf("Error reading conversation: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
|
||||
// create the message
|
||||
msg := &Message{
|
||||
ID: uuid.New().String(),
|
||||
SentAt: s.Time(),
|
||||
Text: req.Text,
|
||||
AuthorID: req.AuthorId,
|
||||
ConversationID: req.ConversationId,
|
||||
}
|
||||
if err := tx.Create(msg).Error; err != nil {
|
||||
logger.Errorf("Error creating message: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
|
||||
// serialize the response
|
||||
// create the message
|
||||
msg := &Message{
|
||||
ID: req.Id,
|
||||
SentAt: s.Time(),
|
||||
Text: req.Text,
|
||||
AuthorID: req.AuthorId,
|
||||
ConversationID: req.ConversationId,
|
||||
}
|
||||
if len(msg.ID) == 0 {
|
||||
msg.ID = uuid.New().String()
|
||||
}
|
||||
if err := s.DB.Create(msg).Error; err == nil {
|
||||
rsp.Message = msg.Serialize()
|
||||
return nil
|
||||
})
|
||||
} else if !strings.Contains(err.Error(), "messages_pkey") {
|
||||
logger.Errorf("Error creating message: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
|
||||
// a message already exists with this id
|
||||
var existing Message
|
||||
if err := s.DB.Where(&Message{ID: msg.ID}).First(&existing).Error; err != nil {
|
||||
logger.Errorf("Error creating message: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
|
||||
}
|
||||
rsp.Message = existing.Serialize()
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user