Files
mchat/ai-chat-service/chat-server/data/chat_records.go
2026-04-10 11:12:10 +00:00

60 lines
1.3 KiB
Go

package data
import (
predis "ai-chat-service/pkg/db/redis"
"context"
"encoding/json"
redis "github.com/redis/go-redis/v9"
)
type IChatRecordsData interface {
Add(record *ChatRecord) error
GetById(id string) (record *ChatRecord, err error)
}
type ChatRecord struct {
ID string `json:"-"`
Question string `json:"q"`
Answer string `json:"a"`
}
type chatRecordsData struct{}
func NewChatRecordsData() IChatRecordsData {
return &chatRecordsData{}
}
func (data *chatRecordsData) Add(record *ChatRecord) error {
client := predis.GetPool().Get()
defer predis.GetPool().Put(client)
payload, err := json.Marshal(&ChatRecord{
Question: record.Question,
Answer: record.Answer,
})
if err != nil {
return err
}
return client.Set(context.Background(), predis.GetKey("qa", record.ID), string(payload), 0).Err()
}
func (data *chatRecordsData) GetById(id string) (*ChatRecord, error) {
client := predis.GetPool().Get()
defer predis.GetPool().Put(client)
value, err := client.Get(context.Background(), predis.GetKey("qa", id)).Result()
if err == redis.Nil {
return nil, nil
}
if err != nil {
return nil, err
}
record := &ChatRecord{ID: id}
if err = json.Unmarshal([]byte(value), record); err != nil {
return nil, err
}
return record, nil
}