blob: 38e0637f5a37894ccb21b378d74c2fef16b0773b [file] [log] [blame]
giolekva62b93bd2020-05-02 08:49:23 +04001package importer
giolekva60e87d32020-05-01 23:07:42 +04002
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io/ioutil"
9 "net/http"
10
11 "github.com/golang/glog"
12 "github.com/itaysk/regogo"
13)
14
15var jsonContentType = "application/json"
16
17var addImgTmpl = `mutation {
18 addImage(input: [{ objectPath: %s }]) {
19 image {
20 id
21 }
22 }
23}`
24
25type Query struct {
26 Query string
27}
28
29func EventToQuery(event string) (Query, error) {
30 key, err := regogo.Get(event, "input.Key")
31 if err != nil {
32 return Query{}, err
33 }
34 keyStr := key.String()
35 if keyStr == "" {
36 return Query{}, errors.New("Key not found")
37 }
38 objectPath, err := json.Marshal(key.String())
39 if err != nil {
40 return Query{}, err
41 }
42 return Query{fmt.Sprintf(addImgTmpl, objectPath)}, nil
43}
44
45type Handler struct {
46 ApiAddr string
47}
48
49func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
50 body, err := ioutil.ReadAll(r.Body)
51 if err != nil {
52 glog.Error(err)
53 http.Error(w, "Could not read HTTP request body", http.StatusBadRequest)
54 return
55 }
56 if len(body) == 0 {
57 // Just a health check from Minio
58 return
59 }
60 bodyStr := string(body)
61 glog.Infof("Received event from Minio: %s", bodyStr)
62 query, err := EventToQuery(bodyStr)
63 if err != nil {
64 glog.Error(err)
65 http.Error(w, "INTERNAL", http.StatusBadRequest)
66 return
67 }
68 glog.Info(query)
69 queryJson, err := json.Marshal(query)
70 if err != nil {
71 panic(err)
72 }
73 resp, err := http.Post(h.ApiAddr, jsonContentType, bytes.NewReader(queryJson))
74 if err != nil {
75 glog.Error(err)
76 http.Error(w, "Query failed", http.StatusInternalServerError)
77 return
78 }
79 if resp.StatusCode != http.StatusOK {
80 glog.Error(resp.StatusCode)
81 http.Error(w, "Query failed", resp.StatusCode)
82 return
83 }
84 respBody, err := ioutil.ReadAll(resp.Body)
85 if err != nil {
86 panic(err)
87 }
88 glog.Info(string(respBody))
89}