Files
supermarket/internal/store/store.go
T
2026-04-29 06:55:00 -06:00

66 lines
1.2 KiB
Go

package store
import (
"encoding/json"
"fmt"
"os"
"time"
)
type GeneratedPost struct {
ID string `json:"id"`
AppName string `json:"app_name"`
Content string `json:"content"`
SourceURL string `json:"source_url,omitempty"`
GeneratedAt time.Time `json:"generated_at"`
}
type Store struct {
Posts []GeneratedPost `json:"posts"`
path string
}
func Load(path string) (*Store, error) {
s := &Store{path: path}
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return s, nil
}
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, s); err != nil {
return nil, err
}
s.path = path
return s, nil
}
func (s *Store) Save() error {
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return os.WriteFile(s.path, data, 0644)
}
func (s *Store) Add(appName, content, sourceURL string) {
s.Posts = append(s.Posts, GeneratedPost{
ID: fmt.Sprintf("%d", time.Now().UnixNano()),
AppName: appName,
Content: content,
SourceURL: sourceURL,
GeneratedAt: time.Now(),
})
}
func (s *Store) Remove(ids map[string]bool) {
kept := s.Posts[:0]
for _, p := range s.Posts {
if !ids[p.ID] {
kept = append(kept, p)
}
}
s.Posts = kept
}