/
sample.go
73 lines (60 loc) · 1.99 KB
/
sample.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
package models
import (
"github.com/hiroykam/goa-sample/models/entities"
"github.com/hiroykam/goa-sample/sample_error"
"github.com/jinzhu/gorm"
)
type SampleModel struct {
db *gorm.DB
}
func (m SampleModel) TableName() string {
return "samples"
}
func NewSampleModel(db *gorm.DB) *SampleModel {
return &SampleModel{
db: db,
}
}
func (m *SampleModel) Get(id int, userId int) (*entities.Sample, *sample_error.SampleError) {
var native entities.Sample
db := m.db.Table(m.TableName()).Where("id = ? AND user_id = ?", id, userId).First(&native)
if db.Error == gorm.ErrRecordNotFound {
return nil, sample_error.NewSampleError(sample_error.NotFoundError, db.Error.Error())
} else if db.Error != nil {
return nil, sample_error.NewSampleError(sample_error.InternalError, db.Error.Error())
}
return &native, nil
}
func (m *SampleModel) List(userId int) ([]*entities.Sample, *sample_error.SampleError) {
var objs []*entities.Sample
db := m.db.Table(m.TableName()).Where("user_id = ?", userId).Find(&objs)
if db.Error != nil {
return nil, sample_error.NewSampleError(sample_error.InternalError, db.Error.Error())
}
if len(objs) > 0 {
return objs, nil
}
return nil, sample_error.NewSampleError(sample_error.NotFoundError, "list is empty")
}
func (m *SampleModel) Add(s *entities.Sample) *sample_error.SampleError {
db := m.db.Create(s)
if db.Error != nil {
return sample_error.NewSampleError(sample_error.InternalError, db.Error.Error())
}
return nil
}
func (m *SampleModel) Update(s *entities.Sample) *sample_error.SampleError {
db := m.db.Table(m.TableName()).Where("id = ?", s.ID).UpdateColumn(s)
if db.Error != nil {
return sample_error.NewSampleError(sample_error.InternalError, db.Error.Error())
}
return nil
}
func (m *SampleModel) Delete(id int, userId int) *sample_error.SampleError {
var obj entities.Sample
db := m.db.Where("user_id = ?", userId).Delete(&obj, id)
if db.Error != nil {
return sample_error.NewSampleError(sample_error.InternalError, db.Error.Error())
}
return nil
}