blob: 5b310b6301c93505964f161289432a4879b6ee4f [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 {
giolekvacc3938e2020-05-02 13:14:56 +040026 Query string `json:"query"`
giolekva60e87d32020-05-01 23:07:42 +040027}
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 }
giolekvacc3938e2020-05-02 13:14:56 +040073 glog.Infof("Query obj: %s", queryJson)
giolekva60e87d32020-05-01 23:07:42 +040074 resp, err := http.Post(h.ApiAddr, jsonContentType, bytes.NewReader(queryJson))
75 if err != nil {
76 glog.Error(err)
77 http.Error(w, "Query failed", http.StatusInternalServerError)
78 return
79 }
80 if resp.StatusCode != http.StatusOK {
81 glog.Error(resp.StatusCode)
82 http.Error(w, "Query failed", resp.StatusCode)
83 return
84 }
85 respBody, err := ioutil.ReadAll(resp.Body)
86 if err != nil {
87 panic(err)
88 }
89 glog.Info(string(respBody))
90}