ezshare/store/memory.go
2021-12-04 11:30:42 +01:00

67 lines
1.3 KiB
Go

package store
import (
"sync"
"gitea.benny.dog/torjus/ezshare/pb"
"github.com/google/uuid"
)
var _ FileStore = &MemoryFileStore{}
type MemoryFileStore struct {
filesLock sync.RWMutex
files map[string]*pb.File
}
func NewMemoryFileStore() *MemoryFileStore {
return &MemoryFileStore{files: make(map[string]*pb.File)}
}
func (s *MemoryFileStore) GetFile(id string) (*pb.File, error) {
s.filesLock.RLock()
defer s.filesLock.RUnlock()
if file, ok := s.files[id]; ok {
return file, nil
}
return nil, ErrNoSuchFile
}
func (s *MemoryFileStore) StoreFile(file *pb.File) (string, error) {
s.filesLock.Lock()
defer s.filesLock.Unlock()
id := uuid.Must(uuid.NewRandom()).String()
file.FileId = id
s.files[id] = file
return id, nil
}
func (s *MemoryFileStore) DeleteFile(id string) error {
s.filesLock.Lock()
defer s.filesLock.Unlock()
if _, ok := s.files[id]; !ok {
return ErrNoSuchFile
}
delete(s.files, id)
return nil
}
func (s *MemoryFileStore) ListFiles() ([]*pb.ListFilesResponse_ListFileInfo, error) {
s.filesLock.RLock()
defer s.filesLock.RUnlock()
var response []*pb.ListFilesResponse_ListFileInfo
for _, f := range s.files {
response = append(response, &pb.ListFilesResponse_ListFileInfo{FileId: f.FileId, Metadata: f.Metadata})
}
return response, nil
}