blob: 81dfdf1527fe391ce236a350eb9092653753b80c [file] [log] [blame]
giolekvaf89e0462020-05-02 17:47:06 +04001package events
2
giolekvad2618252020-05-02 19:39:02 +04003import (
4 "bytes"
5 "encoding/json"
6 // "errors"
7 // "fmt"
8 "io/ioutil"
9 "net/http"
10
11 "github.com/golang/glog"
12)
13
14var jsonContentType = "application/json"
15
giolekvaf89e0462020-05-02 17:47:06 +040016type query struct {
giolekvad2618252020-05-02 19:39:02 +040017 Query string `json:"query"`
giolekvaf89e0462020-05-02 17:47:06 +040018}
19
giolekvad2618252020-05-02 19:39:02 +040020var getAllNewImageEventsTmpl = `{
21 queryImageEvent(filter: {
22 state: {
23 eq: NEW
24 le: NEW
25 lt: NEW
26 ge: NEW
27 gt: NEW
28 }
29 }) {
30 id
31 node {
32 id
33 }
34 }
35}`
36
giolekvaf89e0462020-05-02 17:47:06 +040037// Implements EventStore
38type GraphQLClient struct {
39 apiAddr string
40}
41
42func NewGraphQLClient(apiAddr string) EventStore {
43 return &GraphQLClient{apiAddr}
44}
45
giolekvad2618252020-05-02 19:39:02 +040046type location struct {
47 Line int `json:"line"`
48 Column int `json:"column"`
49}
50
51type gqlError struct {
52 Message string `json:"message"`
53 Locations []location `json:"location"`
54}
55
56type gqlNode struct {
57 Id string `json:"id"`
58}
59
60type gqlEvent struct {
61 Id string `json:"id"`
62 State string `json:"state"`
63 Node gqlNode `json:"node"`
64}
65
66type gqlData struct {
67 Events []gqlEvent `json:"queryImageEvent"`
68}
69
70type queryResp struct {
71 Errors []gqlError `json:"errors"`
72 Data gqlData `json:"data"`
73}
74
giolekvaf89e0462020-05-02 17:47:06 +040075func (c *GraphQLClient) GetEventsInState(state EventState) ([]Event, error) {
giolekvad2618252020-05-02 19:39:02 +040076 q := query{getAllNewImageEventsTmpl}
77 qJson, err := json.Marshal(q)
78 if err != nil {
79 return nil, err
80 }
81 resp, err := http.Post(c.apiAddr, jsonContentType, bytes.NewReader(qJson))
82 if err != nil {
83 return nil, err
84 }
85 respBody, err := ioutil.ReadAll(resp.Body)
86 if err != nil {
87 return nil, err
88 }
89 glog.Info(string(respBody))
90 var gqlResp gqlData
91 err = json.Unmarshal(respBody, &gqlResp)
92 if err != nil {
93 return nil, err
94 }
95 // if len(gqlResp.Errors) != 0 {
96 // return nil, errors.New(fmt.Sprintf("%v", gqlResp.Errors))
97 // }
98 var events []Event
99 for _, e := range gqlResp.Events {
100 events = append(events, Event{e.Id, EventStateNew, e.Node.Id})
101 }
102 return events, nil
giolekvaf89e0462020-05-02 17:47:06 +0400103}