ducky/devices

Paddy 2015-11-20 Parent:34130c700842 Child:74dbc04879a7

9:f5a9d5f8f28d Go to Latest

ducky/devices/memstore.go

Separate out StorerFactory into its own interface. We had previously included a Factory and Destroy method in the Storer interface, but it makes more sense to separate those out into a StorerFactory interface. This lets us avoid the impression that we're using the same instance of a Storer for every test, separates the test methods away from the methods that are actually used in prod, and hides them from Godoc. What's not to like?

History
paddy@4 1 package devices
paddy@4 2
paddy@4 3 import (
paddy@4 4 "sync"
paddy@4 5
paddy@4 6 "code.secondbit.org/uuid.hg"
paddy@4 7 "golang.org/x/net/context"
paddy@4 8 )
paddy@4 9
paddy@4 10 type Memstore struct {
paddy@4 11 devices map[string]Device
paddy@4 12 lock sync.RWMutex
paddy@4 13 }
paddy@4 14
paddy@4 15 func NewMemstore() *Memstore {
paddy@4 16 return &Memstore{
paddy@4 17 devices: map[string]Device{},
paddy@4 18 }
paddy@4 19 }
paddy@4 20
paddy@4 21 func (m *Memstore) GetDevices(ids []uuid.ID, c context.Context) (map[string]Device, error) {
paddy@4 22 m.lock.RLock()
paddy@4 23 defer m.lock.RUnlock()
paddy@4 24
paddy@4 25 results := map[string]Device{}
paddy@4 26
paddy@4 27 for _, id := range ids {
paddy@4 28 device, ok := m.devices[id.String()]
paddy@4 29 if !ok {
paddy@4 30 continue
paddy@4 31 }
paddy@4 32 results[id.String()] = device
paddy@4 33 }
paddy@4 34 return results, nil
paddy@4 35 }
paddy@4 36
paddy@4 37 func (m *Memstore) UpdateDevice(change DeviceChange, c context.Context) error {
paddy@4 38 return nil
paddy@4 39 }
paddy@4 40
paddy@4 41 func (m *Memstore) DeleteDevices(id []uuid.ID, c context.Context) error {
paddy@4 42 return nil
paddy@4 43 }
paddy@4 44
paddy@4 45 func (m *Memstore) CreateDevices(devices []Device, c context.Context) error {
paddy@4 46 m.lock.Lock()
paddy@4 47 defer m.lock.Unlock()
paddy@4 48
paddy@4 49 for _, device := range devices {
paddy@5 50 if _, ok := m.devices[device.ID.String()]; ok {
paddy@5 51 return ErrDeviceAlreadyExists(device.ID)
paddy@5 52 }
paddy@5 53 }
paddy@5 54
paddy@5 55 for _, device := range devices {
paddy@4 56 m.devices[device.ID.String()] = device
paddy@4 57 }
paddy@4 58 return nil
paddy@4 59 }
paddy@4 60
paddy@4 61 func (m *Memstore) ListDevicesByOwner(user uuid.ID, c context.Context) ([]Device, error) {
paddy@8 62 var devices []Device
paddy@8 63 for _, device := range m.devices {
paddy@8 64 if !device.Owner.Equal(user) {
paddy@8 65 continue
paddy@8 66 }
paddy@8 67 devices = append(devices, device)
paddy@8 68 }
paddy@8 69 return devices, nil
paddy@4 70 }