This repository has been archived by the owner on May 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoperations_insert.go
77 lines (65 loc) · 1.85 KB
/
operations_insert.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
package bucket
import (
"context"
"reflect"
"github.com/couchbase/gocb"
"github.com/rs/xid"
)
func (h *Handler) Insert(ctx context.Context, typ, id string, q interface{}, ttl uint32) (Cas, string, error) {
if id == "" {
id = xid.New().String()
}
kv := h.getSubDocuments(typ, id, q, nil)
var ops []gocb.BulkOp
for k, v := range kv {
key := h.state.getDocumentKey(k, id)
ops = append(ops, &gocb.InsertOp{Key: key, Value: v, Expiry: ttl})
}
err := h.state.bucket.Do(ops)
return nil, id, err
}
func (h *Handler) getSubDocuments(typ, id string, q interface{}, parent *documentMeta) map[string]map[string]interface{} {
var documents = make(map[string]map[string]interface{})
var metaField = &meta{
ParentDocument: parent,
Type: typ,
}
var rv = reflect.ValueOf(q)
var rt = rv.Type()
if rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return documents
}
rv = reflect.Indirect(rv)
rt = rv.Type()
}
var fields = make(map[string]interface{})
for i := 0; i < rt.NumField(); i++ {
rvField := rv.Field(i)
rtField := rt.Field(i)
if tag, ok := rtField.Tag.Lookup(tagReferenced); ok {
h.buildDocuments(typ, id, tag, rvField.Interface(), metaField, documents)
} else {
if j, ok := rtField.Tag.Lookup(tagJSON); ok && j != "-" {
fields[removeOmitempty(j)] = rvField.Interface()
}
}
}
fields[metaFieldName] = metaField
documents[typ] = fields
return documents
}
func (h *Handler) buildDocuments(typ, id, tag string, sub interface{}, metaField *meta, documents map[string]map[string]interface{}) {
currentKey := h.state.getDocumentKey(typ, id)
current := documentMeta{
Type: typ,
ID: id,
Key: currentKey,
}
subDocuments := h.getSubDocuments(tag, id, sub, ¤t)
for k, v := range subDocuments {
childKey := h.state.getDocumentKey(k, id)
metaField.AddChildDocument(childKey, k, id)
documents[k] = v
}
}