-
Notifications
You must be signed in to change notification settings - Fork 0
/
updater.go
65 lines (61 loc) · 1.72 KB
/
updater.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
package writer
import (
"context"
"fmt"
"reflect"
es "github.com/core-go/elasticsearch"
"github.com/elastic/go-elasticsearch/v8"
)
type Updater[T any] struct {
client *elasticsearch.Client
index string
idx int
Map func(T)
isPointer bool
FieldMap []es.FieldMap
}
func NewUpdater[T any](client *elasticsearch.Client, index string, opts ...func(T)) *Updater[T] {
return NewUpdaterWithIdName[T](client, index, "", opts...)
}
func NewUpdaterWithIdName[T any](client *elasticsearch.Client, index string, idFieldName string, opts ...func(T)) *Updater[T] {
var t T
modelType := reflect.TypeOf(t)
isPointer := false
if modelType.Kind() == reflect.Ptr {
modelType = modelType.Elem()
isPointer = true
}
var idx int
if len(idFieldName) == 0 {
idx, _, _ = es.FindIdField(modelType)
if idx < 0 {
panic("Require Id field of " + modelType.Name() + " struct define _id bson tag.")
}
} else {
idx, _ = es.FindFieldByName(modelType, idFieldName)
if idx < 0 {
panic(fmt.Sprintf("%s struct requires id field which id name is '%s'", modelType.Name(), idFieldName))
}
}
idField := modelType.Field(idx)
if idField.Type.String() != "string" {
panic(fmt.Sprintf("%s type of %s struct must be string", modelType.Field(idx).Name, modelType.Name()))
}
var mp func(T)
if len(opts) >= 1 {
mp = opts[0]
}
return &Updater[T]{client: client, index: index, idx: idx, Map: mp, isPointer: isPointer}
}
func (w *Updater[T]) Write(ctx context.Context, model T) error {
if w.Map != nil {
w.Map(model)
}
vo := reflect.ValueOf(model)
if w.isPointer {
vo = reflect.Indirect(vo)
}
id := vo.Field(w.idx).Interface().(string)
_, err := es.Update(ctx, w.client, w.index, es.BuildBody(model, w.FieldMap), id)
return err
}