-
Notifications
You must be signed in to change notification settings - Fork 0
/
elasticsearch.go
60 lines (45 loc) · 1.09 KB
/
elasticsearch.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
package creates
import (
"context"
"strings"
"time"
"github.com/goccy/go-json"
"github.com/KejawenLab/bima/v4"
"github.com/KejawenLab/bima/v4/events"
"github.com/KejawenLab/bima/v4/models"
"github.com/olivere/elastic/v7"
)
type Elasticsearch struct {
Service string
Elasticsearch *elastic.Client
}
func (c *Elasticsearch) Handle(event interface{}) interface{} {
e := event.(*events.Model)
if c.Elasticsearch == nil {
return e
}
m := e.Data.(models.GormModel)
var index strings.Builder
index.WriteString(c.Service)
index.WriteString("_")
index.WriteString(m.TableName())
result := make(chan error)
go func(r chan<- error) {
data, _ := json.Marshal(e.Data)
_, err := c.Elasticsearch.Index().Index(index.String()).BodyJson(string(data)).Do(context.Background())
r <- err
}(result)
go func(r <-chan error) {
if <-r == nil {
m.SetSyncedAt(time.Now())
e.Repository.Update(m)
}
}(result)
return e
}
func (u *Elasticsearch) Listen() string {
return events.AfterCreateEvent.String()
}
func (c *Elasticsearch) Priority() int {
return bima.HighestPriority + 1
}