generated from VLADIMIR/template
add story service
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package story_storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"evening_detective/internal/services/story_service"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type service struct {
|
||||
filepath string
|
||||
}
|
||||
|
||||
func NewStoryStorage(filepath string) story_service.IStoryStorage {
|
||||
return &service{
|
||||
filepath: filepath,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *service) Load(ctx context.Context) (*story_service.Story, error) {
|
||||
data, err := os.ReadFile(s.filepath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("story file %s not found", s.filepath)
|
||||
}
|
||||
log.Printf("load story from: %s", s.filepath)
|
||||
story := &story_service.Story{}
|
||||
if err := json.Unmarshal(data, story); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return story, nil
|
||||
}
|
||||
|
||||
func (s *service) Save(ctx context.Context, story *story_service.Story) error {
|
||||
data, err := json.Marshal(story)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(s.filepath, data, 0x777); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("save story to: %s", s.filepath)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user