// Package store keeps expenses in a JSON file. Its methods may be called by // many requests at the same time. // // This is the starter. Open, List and save are finished. The TODOs are in Get, // Add and Delete. package store import ( "encoding/json" "errors" "fmt" "os" "slices" "strings" "sync" "expenses/internal/expense" ) // ErrNotFound is returned for an ID that the store does not have. var ErrNotFound = errors.New("expense not found") // fileData is what the JSON file holds. NextID is kept in the file, so that an // ID is never used twice, even after the newest expense is deleted. type fileData struct { NextID int `json:"next_id"` Expenses []expense.Expense `json:"expenses"` } // File is a store saved to a JSON file. Make one with Open. type File struct { // mu protects everything below it. mu sync.Mutex filename string data fileData } // Open loads the store from a file. A file that does not exist yet gives an // empty store. A file that cannot be read or understood is an error. func Open(filename string) (*File, error) { s := &File{filename: filename, data: fileData{NextID: 1, Expenses: []expense.Expense{}}} content, err := os.ReadFile(filename) if errors.Is(err, os.ErrNotExist) { return s, nil } if err != nil { return nil, err } err = json.Unmarshal(content, &s.data) if err != nil { return nil, fmt.Errorf("%s is not valid: %w", filename, err) } return s, nil } // List returns a copy of all the expenses, oldest date first. func (s *File) List() []expense.Expense { s.mu.Lock() defer s.mu.Unlock() list := slices.Clone(s.data.Expenses) slices.SortFunc(list, byDate) return list } // byDate sorts expenses by date, and expenses on the same day by ID. A date // like 2026-11-03 sorts correctly as text. func byDate(a expense.Expense, b expense.Expense) int { if a.Date != b.Date { return strings.Compare(a.Date, b.Date) } return a.ID - b.ID } // Get returns the expense with this ID, or ErrNotFound. func (s *File) Get(id int) (expense.Expense, error) { // TODO: lock, as List does. Return the expense with this ID, or // ErrNotFound if there is none. return expense.Expense{}, errors.New("TODO: Get is not written yet") } // Add gives the expense the next ID, saves it, and returns it with its ID. If // saving fails, the store stays as it was. func (s *File) Add(e expense.Expense) (expense.Expense, error) { // TODO: lock. Give e the ID s.data.NextID. Make an updated fileData with // NextID one larger and a copy of the expenses with e at the end. Save it, // and only if that worked, keep it in s.data and return e. return expense.Expense{}, errors.New("TODO: Add is not written yet") } // Delete removes the expense with this ID, or returns ErrNotFound. If saving // fails, the store stays as it was. func (s *File) Delete(id int) error { // TODO: lock. Find the index with slices.IndexFunc, or return ErrNotFound. // Make an updated fileData with the same NextID and a copy of the expenses // without that one (slices.Delete on a slices.Clone). Save it, and only if // that worked, keep it. return errors.New("TODO: Delete is not written yet") } // save writes a temporary file, then renames it over the real one, so that a // crash in the middle never leaves half a file. func save(filename string, data fileData) error { content, err := json.MarshalIndent(data, "", " ") if err != nil { return fmt.Errorf("could not save: %w", err) } temporary := filename + ".tmp" err = os.WriteFile(temporary, content, 0644) if err != nil { return fmt.Errorf("could not save: %w", err) } err = os.Rename(temporary, filename) if err != nil { return fmt.Errorf("could not save: %w", err) } return nil }