|
| 1 | +package inmem |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sync" |
| 6 | + |
| 7 | + gopher "github.com/friendsofgo/gopher-api/pkg" |
| 8 | +) |
| 9 | + |
| 10 | +type gopherRepository struct { |
| 11 | + mtx sync.RWMutex |
| 12 | + gophers map[string]*gopher.Gopher |
| 13 | +} |
| 14 | + |
| 15 | +func NewGopherRepository(gophers map[string]*gopher.Gopher) gopher.GopherRepository { |
| 16 | + if gophers == nil { |
| 17 | + gophers = make(map[string]*gopher.Gopher) |
| 18 | + } |
| 19 | + |
| 20 | + return &gopherRepository{ |
| 21 | + gophers: gophers, |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +func (r *gopherRepository) CreateGopher(g *gopher.Gopher) error { |
| 26 | + r.mtx.Lock() |
| 27 | + defer r.mtx.Unlock() |
| 28 | + if err := r.checkIfExists(g.ID); err != nil { |
| 29 | + return err |
| 30 | + } |
| 31 | + r.gophers[g.ID] = g |
| 32 | + return nil |
| 33 | +} |
| 34 | + |
| 35 | +func (r *gopherRepository) FetchGophers() ([]*gopher.Gopher, error) { |
| 36 | + r.mtx.Lock() |
| 37 | + defer r.mtx.Unlock() |
| 38 | + values := make([]*gopher.Gopher, 0, len(r.gophers)) |
| 39 | + for _, value := range r.gophers { |
| 40 | + values = append(values, value) |
| 41 | + } |
| 42 | + return values, nil |
| 43 | +} |
| 44 | + |
| 45 | +func (r *gopherRepository) DeleteGopher(ID string) error { |
| 46 | + r.mtx.Lock() |
| 47 | + defer r.mtx.Unlock() |
| 48 | + delete(r.gophers, ID) |
| 49 | + |
| 50 | + return nil |
| 51 | +} |
| 52 | + |
| 53 | +func (r *gopherRepository) UpdateGopher(ID string, g *gopher.Gopher) error { |
| 54 | + r.mtx.Lock() |
| 55 | + defer r.mtx.Unlock() |
| 56 | + r.gophers[ID] = g |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +func (r *gopherRepository) FetchGopherByID(ID string) (*gopher.Gopher, error) { |
| 61 | + r.mtx.Lock() |
| 62 | + defer r.mtx.Unlock() |
| 63 | + |
| 64 | + for _, v := range r.gophers { |
| 65 | + if v.ID == ID { |
| 66 | + return v, nil |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return nil, fmt.Errorf("The ID %s doesn't exist", ID) |
| 71 | +} |
| 72 | + |
| 73 | +func (r *gopherRepository) checkIfExists(ID string) error { |
| 74 | + for _, v := range r.gophers { |
| 75 | + if v.ID == ID { |
| 76 | + return fmt.Errorf("The gopher %s is already exist", ID) |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return nil |
| 81 | +} |
0 commit comments