forked from dinofizz/todo-api-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gormdb.go
97 lines (87 loc) · 2.53 KB
/
gormdb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"errors"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"strconv"
)
type gormdb struct {
db *gorm.DB
dialect string
connectionString string
}
func (s *gormdb) init() {
gormdb, err := gorm.Open(s.dialect, s.connectionString)
if err != nil {
fmt.Println(err)
panic(fmt.Sprintf("failed to connect to %s Database with connection string %s", s.dialect, s.connectionString))
}
s.db = gormdb
s.db.AutoMigrate(&GormItem{})
}
func (s *gormdb) createItem(item Item) (Item, error) {
gtd := &GormItem{Description: item.Description, Completed: item.Completed}
if err := s.db.Create(gtd).Error; err != nil {
return Item{}, err
}
id := strconv.FormatUint(uint64(gtd.ID), 10)
return Item{Description: gtd.Description, Completed: gtd.Completed, Id: id}, nil
}
func (s *gormdb) updateItem(id string, td Item) (Item, error) {
uintId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
return Item{}, errors.New("Invalid ID type.")
}
var gtd GormItem
if err := s.db.First(>d, uintId).Error; gorm.IsRecordNotFoundError(err) {
return Item{}, &ErrorItemNotFound{Id: id}
} else if err != nil {
return Item{}, err
}
s.db.Model(>d).Update("Completed", td.Completed).Update("Description", td.Description)
return Item{Description: gtd.Description, Completed: gtd.Completed, Id: id}, nil
}
func (s *gormdb) deleteItem(id string) error {
uintId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
return errors.New("Invalid ID type.")
}
var gtd GormItem
if err := s.db.First(>d, uintId).Error; gorm.IsRecordNotFoundError(err) {
return &ErrorItemNotFound{Id: id}
} else if err != nil {
return err
}
s.db.Delete(>d)
return nil
}
func (s *gormdb) getItem(id string) (Item, error) {
uintId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
return Item{}, errors.New("Invalid ID type.")
}
var gtd GormItem
if err := s.db.First(>d, uintId).Error; gorm.IsRecordNotFoundError(err) {
return Item{}, &ErrorItemNotFound{Id: id}
} else if err != nil {
return Item{}, err
}
return Item{Description: gtd.Description, Completed: gtd.Completed, Id: id}, nil
}
func (s *gormdb) allItems() ([]Item, error) {
var gtds []GormItem
if err := s.db.Find(>ds).Error; err != nil {
return make([]Item, 0), err
}
tds := make([]Item, len(gtds))
for i, v := range gtds {
id := strconv.FormatUint(uint64(v.ID), 10)
tds[i] = Item{Description: v.Description, Completed: v.Completed, Id: id}
}
return tds, nil
}
func (s *gormdb) close() {
s.db.Close()
}