-
Notifications
You must be signed in to change notification settings - Fork 4
/
crud_gorm.go
225 lines (182 loc) · 4.92 KB
/
crud_gorm.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// gorm_handlers provides basic methods to interact with
// database using GORM. https://github.com/jinzhu/gorm
package goal
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql" // Driver for mysql
_ "github.com/lib/pq" // Driver for postgres
_ "github.com/mattn/go-sqlite3" // Driver for sqlite
)
// Global variable to interact with database
var db *gorm.DB
// InitGormDb initializes global variable db
func InitGormDb(newDb *gorm.DB) {
db = newDb
}
// DB returns global variable db
func DB() *gorm.DB {
return db
}
// Read provides basic implementation to retrieve object
// based on request parameters
func Read(rType reflect.Type, request *http.Request) (int, interface{}, error) {
if db == nil {
panic("Database is not initialized yet")
}
// Get assumes url requests always has "id" parameters
vars := mux.Vars(request)
// Retrieve id parameter
id, exists := vars["id"]
if !exists {
err := errors.New("id is required")
return 400, nil, err
}
resource := newObjectWithType(rType)
// Attempt to retrieve from redis first, if not exist, retrieve from
// database and cache it
var err error
if SharedCache != nil {
name := TableName(resource)
redisKey := DefaultCacheKey(name, id)
err = SharedCache.Get(redisKey, resource)
if err == nil && resource != nil {
// Check if resource is authorized
err = CanPerform(resource, request, true)
if err != nil {
return 403, nil, err
}
return 200, resource, nil
}
}
// Retrieve from database
err = db.First(resource, id).Error
if err != nil {
return 500, nil, err
}
// Save to redis
if SharedCache != nil {
key := CacheKey(resource)
SharedCache.Set(key, resource)
}
// Check if resource is authorized
err = CanPerform(resource, request, true)
if err != nil {
return 403, nil, err
}
return 200, resource, nil
}
// Create provides basic implementation to create a record
// into the database
func Create(rType reflect.Type, request *http.Request) (int, interface{}, error) {
if db == nil {
panic("Database is not initialized yet")
}
resource := newObjectWithType(rType)
// Parse request body into resource
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(resource)
if err != nil {
fmt.Println(err)
return 500, nil, err
}
// Save to database
err = db.Create(resource).Error
if err != nil {
return 500, nil, err
}
return 200, resource, nil
}
// Update provides basic implementation to update a record
// inside database
func Update(rType reflect.Type, request *http.Request) (int, interface{}, error) {
if db == nil {
panic("Database is not initialized yet")
}
// Get assumes url requests always has "id" parameters
vars := mux.Vars(request)
// Retrieve id parameter, if error return 400 HTTP error code
id, exists := vars["id"]
if !exists {
err := errors.New("id is required")
return 400, nil, err
}
resource := newObjectWithType(rType)
// Parse request body into updatedObj
updatedObj := newObjectWithType(rType)
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(updatedObj)
if err != nil {
fmt.Println(err)
return 500, nil, err
}
// Retrieve from database
err = db.First(resource, id).Error
if err != nil {
fmt.Println(err)
return 500, nil, err
}
// Check permission
err = CanPerform(resource, request, false)
if err != nil {
return 403, nil, err
}
// Check if this object support revision
current, okCurrent := resource.(Revisioner)
updated, okUpdated := updatedObj.(Revisioner)
if okCurrent && okUpdated {
if updated.CurrentRevision() == 0 {
err = errors.New("revision is required")
return 400, nil, err
}
if !CanMerge(current, updated) {
err = errors.New("conflict")
return 409, resource, err
}
updated.SetNextRevision()
}
// Save to database. Only update fields that is not blank or default values
// http://jinzhu.me/gorm/curd.html#update
err = db.Model(resource).Update(updatedObj).Error
if err != nil {
return 500, nil, err
}
return 200, resource, err
}
// Delete provides basic implementation to delete a record inside
// a database
func Delete(rType reflect.Type, request *http.Request) (int, interface{}, error) {
if db == nil {
panic("Database is not initialized yet")
}
// Get assumes url requests always has "id" parameters
vars := mux.Vars(request)
// Retrieve id parameter, if error return 400 HTTP error code
id, exists := vars["id"]
if !exists {
err := errors.New("id is required")
return 400, nil, err
}
resource := newObjectWithType(rType)
// Retrieve from database
err := db.First(resource, id).Error
if err != nil {
return 500, nil, err
}
// Check permission
err = CanPerform(resource, request, false)
if err != nil {
return 403, nil, err
}
// Delete record, if failed show 500 error code
err = db.Delete(resource, id).Error
if err != nil {
return 500, nil, err
}
return 200, nil, nil
}