library/database/memory.go

80 lines
1.4 KiB
Go
Raw Normal View History

2021-06-26 18:08:35 +00:00
package database
import (
"context"
"fmt"
"sync"
2022-03-05 15:58:15 +00:00
"git.yetaga.in/alazyreader/library/media"
2021-06-26 18:08:35 +00:00
)
type Memory struct {
lock sync.Mutex
2022-03-05 15:58:15 +00:00
shelf []media.Book
2021-06-26 18:08:35 +00:00
}
2022-03-05 15:58:15 +00:00
func (m *Memory) GetAllBooks(_ context.Context) ([]media.Book, error) {
2021-06-26 18:08:35 +00:00
m.lock.Lock()
defer m.lock.Unlock()
if m.shelf == nil {
2022-03-05 15:58:15 +00:00
m.shelf = []media.Book{}
2021-06-26 18:08:35 +00:00
}
return m.shelf, nil
}
2022-03-05 15:58:15 +00:00
func (m *Memory) AddBook(_ context.Context, b *media.Book) error {
2021-06-26 18:08:35 +00:00
m.lock.Lock()
defer m.lock.Unlock()
if m.shelf == nil {
2022-03-05 15:58:15 +00:00
m.shelf = []media.Book{}
2021-06-26 18:08:35 +00:00
}
m.shelf = append(m.shelf, *b)
return nil
}
2022-03-05 15:58:15 +00:00
func (m *Memory) UpdateBook(_ context.Context, old, new *media.Book) error {
2021-06-26 18:08:35 +00:00
m.lock.Lock()
defer m.lock.Unlock()
if m.shelf == nil {
2022-03-05 15:58:15 +00:00
m.shelf = []media.Book{}
2021-06-26 18:08:35 +00:00
return fmt.Errorf("book does not exist")
}
if old.ID != new.ID {
return fmt.Errorf("cannot change book ID")
}
for i := range m.shelf {
if m.shelf[i].ID == old.ID {
m.shelf[i] = *new
return nil
}
}
return fmt.Errorf("book does not exist")
}
2022-03-05 15:58:15 +00:00
func (m *Memory) DeleteBook(_ context.Context, b *media.Book) error {
2021-06-26 18:08:35 +00:00
m.lock.Lock()
defer m.lock.Unlock()
if m.shelf == nil {
2022-03-05 15:58:15 +00:00
m.shelf = []media.Book{}
2021-06-26 18:08:35 +00:00
return fmt.Errorf("book does not exist")
}
for i := range m.shelf {
if m.shelf[i].ID == b.ID {
// reorder slice to remove book quickly
m.shelf[i] = m.shelf[len(m.shelf)-1]
m.shelf = m.shelf[:len(m.shelf)-1]
return nil
}
}
return fmt.Errorf("book does not exist")
}