80 lines
1.4 KiB
Go
80 lines
1.4 KiB
Go
|
package database
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"sync"
|
||
|
|
||
|
"git.yetaga.in/alazyreader/library/book"
|
||
|
)
|
||
|
|
||
|
type Memory struct {
|
||
|
lock sync.Mutex
|
||
|
shelf []book.Book
|
||
|
}
|
||
|
|
||
|
func (m *Memory) GetAllBooks(_ context.Context) ([]book.Book, error) {
|
||
|
m.lock.Lock()
|
||
|
defer m.lock.Unlock()
|
||
|
|
||
|
if m.shelf == nil {
|
||
|
m.shelf = []book.Book{}
|
||
|
}
|
||
|
|
||
|
return m.shelf, nil
|
||
|
}
|
||
|
|
||
|
func (m *Memory) AddBook(_ context.Context, b *book.Book) error {
|
||
|
m.lock.Lock()
|
||
|
defer m.lock.Unlock()
|
||
|
|
||
|
if m.shelf == nil {
|
||
|
m.shelf = []book.Book{}
|
||
|
}
|
||
|
|
||
|
m.shelf = append(m.shelf, *b)
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (m *Memory) UpdateBook(_ context.Context, old, new *book.Book) error {
|
||
|
m.lock.Lock()
|
||
|
defer m.lock.Unlock()
|
||
|
|
||
|
if m.shelf == nil {
|
||
|
m.shelf = []book.Book{}
|
||
|
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")
|
||
|
}
|
||
|
|
||
|
func (m *Memory) DeleteBook(_ context.Context, b *book.Book) error {
|
||
|
m.lock.Lock()
|
||
|
defer m.lock.Unlock()
|
||
|
|
||
|
if m.shelf == nil {
|
||
|
m.shelf = []book.Book{}
|
||
|
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")
|
||
|
}
|