Skip to content

Commit

Permalink
fix: because it was not saved as intended (#3)
Browse files Browse the repository at this point in the history
* fix: because it was not saved as intended

* test: fix, not good solution
  • Loading branch information
hirokisan committed Mar 14, 2023
1 parent d3050f1 commit d97ee29
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
17 changes: 9 additions & 8 deletions message/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ func (m *historicalMessenger) GetReply(
client *openai.Client,
message string,
) (*openai.ChatCompletionMessage, error) {
var messageHistory []openai.ChatCompletionMessage
if err := m.load(&messageHistory); err != nil {
messageHistory, err := m.load()
if err != nil {
return nil, fmt.Errorf("load message history: %w", err)
}

Expand All @@ -49,15 +49,16 @@ func (m *historicalMessenger) GetReply(
// HistoryStore :
type HistoryStore interface {
io.Reader
io.Writer
io.WriterAt
}

// load :
func (m *historicalMessenger) load(messageHistory *[]openai.ChatCompletionMessage) error {
if err := json.NewDecoder(m.store).Decode(&messageHistory); err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("decode: %w", err)
func (m *historicalMessenger) load() ([]openai.ChatCompletionMessage, error) {
var history []openai.ChatCompletionMessage
if err := json.NewDecoder(m.store).Decode(&history); err != nil && !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("decode: %w", err)
}
return nil
return history, nil
}

// update :
Expand All @@ -66,7 +67,7 @@ func (m *historicalMessenger) update(messageHistory []openai.ChatCompletionMessa
if err != nil {
return fmt.Errorf("json marshal: %w", err)
}
if _, err := m.store.Write(bytes); err != nil {
if _, err := m.store.WriteAt(bytes, 0); err != nil {
return fmt.Errorf("write file: %w", err)
}
return nil
Expand Down
11 changes: 10 additions & 1 deletion message/history_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ import (
"github.com/stretchr/testify/require"
)

type testWriter struct {
bytes.Buffer
}

func (w *testWriter) WriteAt(b []byte, _ int64) (n int, err error) {
w.Buffer = *bytes.NewBuffer(b)
return len(b), nil
}

func TestHistoricalMessenger_GetReply(t *testing.T) {
ctx := context.Background()

Expand Down Expand Up @@ -50,7 +59,7 @@ func TestHistoricalMessenger_GetReply(t *testing.T) {

client := testhelper.NewTestClient(server.URL)

var store bytes.Buffer
var store testWriter
messenger := NewHistoricalMessenger(&store)

message := "my name is chatty"
Expand Down

0 comments on commit d97ee29

Please sign in to comment.