From 2192bf4e7774694de01166b4b76d413205caa6b6 Mon Sep 17 00:00:00 2001 From: Fedorov Vladimir Date: Sun, 7 Dec 2025 02:13:48 +0700 Subject: [PATCH] add load and save methods --- .../services/story_service/data_models.go | 2 +- internal/services/story_service/service.go | 28 +++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/internal/services/story_service/data_models.go b/internal/services/story_service/data_models.go index ab6e6da..740dd56 100644 --- a/internal/services/story_service/data_models.go +++ b/internal/services/story_service/data_models.go @@ -8,7 +8,7 @@ type Place struct { Code string `json:"code"` Name string `json:"name"` Text string `json:"text"` - Applications []*Application `json:"applications"` + Applications []*Application `json:"applications,omitempty"` } type Application struct { diff --git a/internal/services/story_service/service.go b/internal/services/story_service/service.go index f820010..955fe89 100644 --- a/internal/services/story_service/service.go +++ b/internal/services/story_service/service.go @@ -15,16 +15,38 @@ type StoryService struct { } func NewStoryService(filepath string) (*StoryService, error) { + s := &StoryService{} + if err := s.Load(filepath); err != nil { + return nil, err + } + return s, nil +} + +func (s *StoryService) Load(filepath string) error { data, err := os.ReadFile(filepath) if err != nil { - return nil, fmt.Errorf("story file %s not found", filepath) + return fmt.Errorf("story file %s not found", filepath) } log.Printf("load story from: %s", filepath) story := &Story{} if err := json.Unmarshal(data, story); err != nil { - return nil, err + return err } - return &StoryService{story: story}, nil + s.story = story + return nil +} + +func (s *StoryService) Save(filepath string) error { + story := s.story + data, err := json.Marshal(story) + if err != nil { + return err + } + if err := os.WriteFile(filepath, data, 0x777); err != nil { + return err + } + log.Printf("save story to: %s", filepath) + return nil } func (s *StoryService) GetPlace(code string) *Place {