-
Notifications
You must be signed in to change notification settings - Fork 3
/
meta.go
283 lines (229 loc) · 6.8 KB
/
meta.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package fire
import (
"reflect"
"strings"
"gopkg.in/mgo.v2/bson"
)
var metaCache = make(map[string]*Meta)
var baseType = reflect.TypeOf(Base{})
var toOneType = reflect.TypeOf(bson.ObjectId(""))
var optionalToOneType = reflect.TypeOf(new(bson.ObjectId))
var toManyType = reflect.TypeOf(make([]bson.ObjectId, 0))
var hasManyType = reflect.TypeOf(HasMany{})
// The HasMany type denotes a has many relationship in a model declaration.
type HasMany struct{}
// A Field contains the meta information about a single field of a model.
type Field struct {
Name string
Type reflect.Type
Kind reflect.Kind
JSONName string
BSONName string
Optional bool
ToOne bool
ToMany bool
HasMany bool
RelName string
RelType string
RelInverse string
index int
}
// Meta stores extracted meta data from a model.
type Meta struct {
Name string
PluralName string
Collection string
Fields []Field
model Model
}
// NewMeta returns the Meta structure for the passed Model.
//
// Note: This method panics if the passed Model has invalid fields and tags.
func NewMeta(model Model) *Meta {
// get type and name
modelType := reflect.TypeOf(model).Elem()
modelName := modelType.String()
// check if meta has already been cached
meta, ok := metaCache[modelName]
if ok {
return meta
}
// create new meta
meta = &Meta{
Name: modelName,
model: model,
}
// iterate through all fields
for i := 0; i < modelType.NumField(); i++ {
structField := modelType.Field(i)
// get fire tag
fireStructTag := structField.Tag.Get("fire")
// check if field is the Base
if structField.Type == baseType {
baseTag := strings.Split(fireStructTag, ":")
// check json tag
if structField.Tag.Get("json") != "-" {
panic(`Expected to find a tag of the form json:"-" on Base`)
}
// check bson tag
if structField.Tag.Get("bson") != ",inline" {
panic(`Expected to find a tag of the form bson:",inline" on Base`)
}
// check tag
if len(baseTag) > 2 || baseTag[0] == "" {
panic(`Expected to find a tag of the form fire:"plural-name[:collection]" on Base`)
}
// infer plural and collection names
meta.PluralName = baseTag[0]
meta.Collection = baseTag[0]
// infer collection
if len(baseTag) == 2 {
meta.Collection = baseTag[1]
}
continue
}
// parse individual tags
fireTags := strings.Split(fireStructTag, ",")
if len(fireStructTag) == 0 {
fireTags = nil
}
// get field type
fieldKind := structField.Type.Kind()
if fieldKind == reflect.Ptr {
fieldKind = structField.Type.Elem().Kind()
}
// prepare field
field := Field{
Name: structField.Name,
Type: structField.Type,
Kind: fieldKind,
JSONName: getJSONFieldName(&structField),
BSONName: getBSONFieldName(&structField),
Optional: structField.Type.Kind() == reflect.Ptr,
index: i,
}
// check if field is a valid to one relationship
if structField.Type == toOneType || structField.Type == optionalToOneType {
if len(fireTags) > 0 && strings.Count(fireTags[0], ":") > 0 {
// check tag
if strings.Count(fireTags[0], ":") > 1 {
panic("Expected to find a tag of the form fire:\"name:type\" on to one relationship")
}
// parse special to one relationship tag
toOneTag := strings.Split(fireTags[0], ":")
// set relationship data
field.ToOne = true
field.RelName = toOneTag[0]
field.RelType = toOneTag[1]
// remove tag
fireTags = fireTags[1:]
}
}
// check if field is a valid to many relationship
if structField.Type == toManyType {
if len(fireTags) > 0 && strings.Count(fireTags[0], ":") > 0 {
// check tag
if strings.Count(fireTags[0], ":") > 1 {
panic("Expected to find a tag of the form fire:\"name:type\" on to many relationship")
}
// parse special to many relationship tag
toManyTag := strings.Split(fireTags[0], ":")
// set relationship data
field.ToMany = true
field.RelName = toManyTag[0]
field.RelType = toManyTag[1]
// remove tag
fireTags = fireTags[1:]
}
}
// check if field is a valid has many relationship
if structField.Type == hasManyType {
// check tag
if len(fireTags) != 1 || strings.Count(fireTags[0], ":") != 2 {
panic(`Expected to find a tag of the form fire:"name:type:inverse" on has many relationship`)
}
// parse special has many relationship tag
hasManyTag := strings.Split(fireTags[0], ":")
// set relationship data
field.HasMany = true
field.RelName = hasManyTag[0]
field.RelType = hasManyTag[1]
field.RelInverse = hasManyTag[2]
// remove tag
fireTags = fireTags[1:]
}
// panic on any additional tags
for _, tag := range fireTags {
panic("Unexpected tag " + tag)
}
// add field
meta.Fields = append(meta.Fields, field)
}
// cache meta
metaCache[modelName] = meta
return meta
}
// FindField returns the first field that has a matching Name, JSONName, or
// BSONName. FindField will return nil if no field has been found.
func (m *Meta) FindField(name string) *Field {
for _, field := range m.Fields {
if field.JSONName == name || field.BSONName == name || field.Name == name {
return &field
}
}
return nil
}
// MustFindField returns the first field that has a matching Name, JSONName, or
// BSONName. MustFindField will panic if no field has been found.
func (m *Meta) MustFindField(name string) *Field {
field := m.FindField(name)
if field == nil {
panic("Field " + name + " not found on " + m.Name)
}
return field
}
// Make returns a pointer to a new zero initialized model e.g. *Post.
//
// Note: Other libraries like mgo might replace the pointer content with a new
// structure, therefore the model eventually needs to be initialized again
// using Init().
func (m *Meta) Make() Model {
pointer := reflect.New(reflect.TypeOf(m.model).Elem()).Interface()
return Init(pointer.(Model))
}
// MakeSlice returns a pointer to a zero length slice of the model e.g. *[]*Post.
//
// Note: Don't forget to initialize the slice using InitSlice() after adding
// elements with libraries like mgo.
func (m *Meta) MakeSlice() interface{} {
slice := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(m.model)), 0, 0)
pointer := reflect.New(slice.Type())
pointer.Elem().Set(slice)
return pointer.Interface()
}
func getJSONFieldName(field *reflect.StructField) string {
tag := field.Tag.Get("json")
values := strings.Split(tag, ",")
// check for "-"
if tag == "-" {
return ""
}
// check first value
if len(tag) > 0 || len(values[0]) > 0 {
return values[0]
}
return field.Name
}
func getBSONFieldName(field *reflect.StructField) string {
tag := field.Tag.Get("bson")
values := strings.Split(tag, ",")
// check for "-"
if tag == "-" {
return ""
}
// check first value
if len(tag) > 0 || len(values[0]) > 0 {
return values[0]
}
return strings.ToLower(field.Name)
}