go-jsonapi-example/internal/storage/storage_car.go

84 lines
1.6 KiB
Go
Raw Normal View History

2021-03-18 18:52:41 +00:00
package storage
import (
"errors"
"fmt"
"net/http"
2021-03-21 11:03:35 +00:00
"sync"
2021-03-18 18:52:41 +00:00
"go-jsonapi-example/internal/model"
"github.com/manyminds/api2go"
)
type CarStorage struct {
2021-03-21 11:03:35 +00:00
mutex sync.RWMutex
cars map[uint64]*model.Car
idCount uint64
2021-03-18 18:52:41 +00:00
}
2021-03-21 11:03:35 +00:00
type Cars []model.Car
func (c Cars) Len() int { return len(c) }
func (c Cars) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c Cars) Less(i, j int) bool { return c[i].ID < c[j].ID }
2021-03-18 18:52:41 +00:00
func NewCarStorage() *CarStorage {
2021-03-21 11:03:35 +00:00
return &CarStorage{cars: make(map[uint64]*model.Car), idCount: 1}
2021-03-18 18:52:41 +00:00
}
2021-03-21 11:03:35 +00:00
func (s CarStorage) GetAll() Cars {
s.mutex.RLock()
defer s.mutex.RUnlock()
result := make(Cars, 0, len(s.cars))
for _, car := range s.cars {
result = append(result, *car)
}
return result
2021-03-18 18:52:41 +00:00
}
2021-03-21 11:03:35 +00:00
func (s CarStorage) GetOne(id uint64) (model.Car, error) {
s.mutex.RLock()
car, ok := s.cars[id]
2021-03-18 18:52:41 +00:00
if ok {
2021-03-21 11:03:35 +00:00
defer s.mutex.RUnlock()
return *car, nil
2021-03-18 18:52:41 +00:00
}
2021-03-21 11:03:35 +00:00
s.mutex.RUnlock()
2021-03-21 11:25:23 +00:00
errMessage := fmt.Sprintf("Car for id %d not found", id)
2021-03-18 18:52:41 +00:00
return model.Car{}, api2go.NewHTTPError(errors.New(errMessage), errMessage, http.StatusNotFound)
}
2021-03-21 11:03:35 +00:00
func (s *CarStorage) Insert(c model.Car) uint64 {
s.mutex.Lock()
defer s.mutex.Unlock()
c.ID = s.idCount
s.cars[s.idCount] = &c
2021-03-18 18:52:41 +00:00
s.idCount++
2021-03-21 11:03:35 +00:00
return c.ID
2021-03-18 18:52:41 +00:00
}
2021-03-21 11:03:35 +00:00
func (s *CarStorage) Delete(id uint64) error {
s.mutex.Lock()
defer s.mutex.Unlock()
2021-03-18 18:52:41 +00:00
_, exists := s.cars[id]
if !exists {
2021-03-21 11:25:23 +00:00
return fmt.Errorf("Car with id %d does not exist", id)
2021-03-18 18:52:41 +00:00
}
delete(s.cars, id)
return nil
}
func (s *CarStorage) Update(c model.Car) error {
2021-03-21 11:03:35 +00:00
s.mutex.Lock()
defer s.mutex.Unlock()
2021-03-18 18:52:41 +00:00
_, exists := s.cars[c.ID]
if !exists {
2021-03-21 11:25:23 +00:00
return fmt.Errorf("Car with id %d does not exist", c.ID)
2021-03-18 18:52:41 +00:00
}
s.cars[c.ID] = &c
return nil
}