fix crash on missing config

This commit is contained in:
Balakrishnan Balasubramanian 2022-10-25 14:39:17 -04:00
parent 5b61498a00
commit c71594f2ad

View File

@ -59,7 +59,7 @@ func (d *Db) Add(i Item) (int, bool) {
func (d *Db) Transact(id int, persist bool, f func(*Item)) error { func (d *Db) Transact(id int, persist bool, f func(*Item)) error {
d.mutex.Lock() d.mutex.Lock()
defer d.mutex.Unlock() defer d.mutex.Unlock()
for i, _ := range d.items { for i := range d.items {
if d.items[i].Id == id { if d.items[i].Id == id {
f(&d.items[i]) f(&d.items[i])
if persist { if persist {
@ -68,7 +68,7 @@ func (d *Db) Transact(id int, persist bool, f func(*Item)) error {
return nil return nil
} }
} }
return fmt.Errorf("Invalid id: %d", id) return fmt.Errorf("invalid id: %d", id)
} }
func (d *Db) save() error { func (d *Db) save() error {
@ -93,11 +93,13 @@ func (d *Db) Save() error {
func Load(path string) (*Db, error) { func Load(path string) (*Db, error) {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
indexMap := map[string]int{}
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
return &Db{ return &Db{
path: path, path: path,
lastId: 0, lastId: 0,
index: indexMap,
}, nil }, nil
} }
return nil, err return nil, err
@ -108,7 +110,6 @@ func Load(path string) (*Db, error) {
return nil, err return nil, err
} }
m := 0 m := 0
indexMap := map[string]int{}
for _, item := range jd.Items { for _, item := range jd.Items {
if item.Id > m { if item.Id > m {
m = item.Id m = item.Id