/
index.go
91 lines (73 loc) · 1.68 KB
/
index.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
package opensearch
import (
"fmt"
"net/http"
"github.com/opensearch-project/opensearch-go/v2/opensearchapi"
)
type MigrationsIndexManagerInterface interface {
Upsert(name string) error
Exists(name string) (bool, error)
Create(name string) error
}
type MigrationsIndexManager struct {
transport opensearchapi.Transport
}
func NewMigrationsIndexManager(transport opensearchapi.Transport) MigrationsIndexManager {
return MigrationsIndexManager{
transport: transport,
}
}
func (m MigrationsIndexManager) Upsert(name string) error {
exists, err := m.Exists(name)
if err != nil {
return err
}
if exists {
return nil
}
return m.Create(name)
}
func (m MigrationsIndexManager) Exists(name string) (bool, error) {
mgr := Migration{
Method: "HEAD",
URL: "/" + name,
}
req, err := mgr.CreateRequest()
if err != nil {
return false, err
}
resp, err := m.transport.Perform(req)
defer closeResponseBody(resp)
if err != nil {
return false, fmt.Errorf("check migrations index Exists request failed: %w", err)
}
return resp.StatusCode == http.StatusOK, nil
}
func (m MigrationsIndexManager) Create(name string) error {
mgr := Migration{
Method: "PUT",
URL: "/" + name,
Body: map[string]any{
"mappings": map[string]any{
"properties": map[string]any{
"version": map[string]any{
"type": "integer",
},
"dirty": map[string]any{
"type": "boolean",
},
},
},
},
}
req, err := mgr.CreateRequest()
if err != nil {
return err
}
resp, err := m.transport.Perform(req)
defer closeResponseBody(resp)
if err != nil {
return fmt.Errorf("create migrations index request failed: %w", err)
}
return ReadErrorFromResponse(resp)
}