|
| 1 | +package notes |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | +) |
| 8 | + |
| 9 | +// A Book allows for management, such as |
| 10 | +// inserting, updating, and deleting notes. |
| 11 | +type Book struct { |
| 12 | + Logger io.Writer // Logger for verbose logging |
| 13 | + |
| 14 | + notes map[int]*Note |
| 15 | + curID int |
| 16 | +} |
| 17 | + |
| 18 | +// Len returns the number of notes in the book. |
| 19 | +func (book *Book) Len() int { |
| 20 | + if book == nil { |
| 21 | + return 0 |
| 22 | + } |
| 23 | + |
| 24 | + return len(book.notes) |
| 25 | +} |
| 26 | + |
| 27 | +// Restore restores the book from the provided reader. |
| 28 | +// The reader should contain a JSON-encoded book. |
| 29 | +func (book *Book) Restore(r io.Reader) error { |
| 30 | + if book == nil { |
| 31 | + return nil |
| 32 | + } |
| 33 | + |
| 34 | + if r == nil { |
| 35 | + return fmt.Errorf("no reader provided") |
| 36 | + } |
| 37 | + |
| 38 | + book.log("[RESTORE]\tstarting:\t(%d)\n", len(book.notes)) |
| 39 | + |
| 40 | + err := json.NewDecoder(r).Decode(book) |
| 41 | + |
| 42 | + if err != nil && err != io.EOF { |
| 43 | + return fmt.Errorf("failed to decode book: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + book.log("[RESTORE]\tfinished:\t(%d)\n", len(book.notes)) |
| 47 | + |
| 48 | + return nil |
| 49 | +} |
| 50 | + |
| 51 | +// Backup backs up the book, in JSON, to the provided writer. |
| 52 | +func (book *Book) Backup(w io.Writer) error { |
| 53 | + if book == nil { |
| 54 | + return nil |
| 55 | + } |
| 56 | + |
| 57 | + if w == nil { |
| 58 | + return fmt.Errorf("no writer provided") |
| 59 | + } |
| 60 | + |
| 61 | + book.log("[BACKUP]\tstarting:\t(%d)\n", len(book.notes)) |
| 62 | + |
| 63 | + enc := json.NewEncoder(w) |
| 64 | + enc.SetIndent("", "\t") |
| 65 | + if err := enc.Encode(book); err != nil { |
| 66 | + return fmt.Errorf("failed to encode book: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + book.log("[BACKUP]\tfinished:\t(%d)\n", len(book.notes)) |
| 70 | + return nil |
| 71 | +} |
| 72 | + |
| 73 | +func (book *Book) log(format string, a ...interface{}) { |
| 74 | + if book == nil || book.Logger == nil { |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + fmt.Fprintf(book.Logger, format, a...) |
| 79 | +} |
0 commit comments