1
|
|
|
package models |
2
|
|
|
|
3
|
|
|
import "errors" |
4
|
|
|
|
5
|
|
|
// Item godoc |
6
|
|
|
type Item struct { |
7
|
|
|
ID int `json:"id,omitempty" bson:"id,omitempty" datastore:"id"` |
8
|
|
|
Title string `json:"title,omitempty" bson:"title,omitempty" datastore:"title"` |
9
|
|
|
IsDone bool `json:"isdone,omitempty" bson:"isdone,omitempty" datastore:"isdone"` |
10
|
|
|
} |
11
|
|
|
|
12
|
|
|
var ( |
13
|
|
|
// ErrNoRecord godoc |
14
|
|
|
ErrNoRecord = errors.New("No matching record found") |
15
|
|
|
// ErrRecordExist godoc |
16
|
|
|
ErrRecordExist = errors.New("Record already exists") |
17
|
|
|
) |
18
|
|
|
|
19
|
|
|
// ItemRepository godoc |
20
|
|
|
type ItemRepository interface { |
21
|
|
|
GetItems() ([]Item, error) |
22
|
|
|
GetItem(int) (Item, error) |
23
|
|
|
CreateItem(Item) error |
24
|
|
|
UpdateItem(Item) error |
25
|
|
|
DeleteItem(int) error |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
// ItemModel godoc |
29
|
|
|
type ItemModel struct { |
30
|
|
|
Repository ItemRepository |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
// GetItems godoc |
34
|
|
|
func (model ItemModel) GetItems() (i []Item, e error) { |
35
|
|
|
i, e = model.Repository.GetItems() |
36
|
|
|
|
37
|
|
|
if i == nil && e == nil { |
38
|
|
|
i = []Item{} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
return |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// GetItem godoc |
45
|
|
|
func (model ItemModel) GetItem(id int) (i Item, e error) { |
46
|
|
|
i, e = model.Repository.GetItem(id) |
47
|
|
|
|
48
|
|
|
if i == (Item{}) && e == nil { |
49
|
|
|
e = ErrNoRecord |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
// CreateItem godoc |
56
|
|
|
func (model ItemModel) CreateItem(newItem Item) error { |
57
|
|
|
i, _ := model.Repository.GetItem(newItem.ID) |
58
|
|
|
|
59
|
|
|
if i.ID == newItem.ID { |
60
|
|
|
return ErrRecordExist |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return model.Repository.CreateItem(newItem) |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// UpdateItem godoc |
67
|
|
|
func (model ItemModel) UpdateItem(updatedItem Item) error { |
68
|
|
|
i, e := model.Repository.GetItem(updatedItem.ID) |
69
|
|
|
|
70
|
|
|
if i == (Item{}) && e == nil { |
71
|
|
|
return ErrNoRecord |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return model.Repository.UpdateItem(updatedItem) |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
// DeleteItem godoc |
78
|
|
|
func (model ItemModel) DeleteItem(id int) error { |
79
|
|
|
i, e := model.Repository.GetItem(id) |
80
|
|
|
|
81
|
|
|
if i == (Item{}) && e == nil { |
82
|
|
|
return ErrNoRecord |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return model.Repository.DeleteItem(id) |
86
|
|
|
} |
87
|
|
|
|