104 lines
2.4 KiB
Go
104 lines
2.4 KiB
Go
package balboa
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"gitlab.dcso.lolcat/go/golistic/xapi"
|
|
"gitlab.dcso.lolcat/go/golistic/xhttp"
|
|
)
|
|
|
|
const (
|
|
headerFieldContentType = "Content-type"
|
|
mimeTypeJSON = "application/json"
|
|
graphqlPath = "/query"
|
|
)
|
|
|
|
// post GraphQL query
|
|
func (c *Client) post(ctx context.Context, query *xapi.GraphQLQuery, dest *xapi.GraphQLPayload) error {
|
|
gqlClient := xapi.NewGraphQLClient(c.addr+graphqlPath, xhttp.OptionTimeout(2*time.Minute))
|
|
err := gqlClient.AddMiddleware(func(ctx context.Context, r *http.Request) error {
|
|
r.Header.Add(headerFieldContentType, mimeTypeJSON)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err = gqlClient.Exec(ctx, query, dest); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Ping Balboa to see whether it is both available and that we can connect
|
|
// and query it.
|
|
func (c *Client) Ping(ctx context.Context) (err error) {
|
|
resp := xapi.GraphQLPayload{}
|
|
query := &xapi.GraphQLQuery{
|
|
Query: queryTest,
|
|
}
|
|
|
|
if err = c.post(ctx, query, &resp); err != nil {
|
|
return err
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// GetAllEntries retrieves all entries for a Balboa query
|
|
func (c *Client) GetAllEntries(ctx context.Context, rrname string, rrtype string, rdata string, limit int32) ([]Entries, error) {
|
|
resp := xapi.GraphQLPayload{}
|
|
query := &xapi.GraphQLQuery{
|
|
Query: queryAllEntries,
|
|
Variables: map[string]interface{}{
|
|
"rrname": rrname,
|
|
"rrtype": rrtype,
|
|
"rdata": rdata,
|
|
"limit": 100,
|
|
},
|
|
}
|
|
|
|
if err := c.post(ctx, query, &resp); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
l := EntriesList{}
|
|
if err := json.Unmarshal(resp.Data, &l); err != nil {
|
|
return nil, fmt.Errorf("json decode: %v", err)
|
|
}
|
|
return l.EntriesListItem, nil
|
|
}
|
|
|
|
// GetEntriesBySensor returns Balboa entries by sensorID
|
|
func (c *Client) GetEntriesBySensor(ctx context.Context, rrname string, rrtype string, rdata string, limit int32, sensorID string) ([]Entries, error) {
|
|
if limit == 0 {
|
|
limit = 100
|
|
}
|
|
resp := xapi.GraphQLPayload{}
|
|
query := &xapi.GraphQLQuery{
|
|
Query: queryAllEntries,
|
|
Variables: map[string]interface{}{
|
|
"rrname": rrname,
|
|
"rrtype": rrtype,
|
|
"rdata": rdata,
|
|
"sensorID": sensorID,
|
|
"limit": limit,
|
|
},
|
|
}
|
|
|
|
if err := c.post(ctx, query, &resp); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
l := EntriesList{}
|
|
if err := json.Unmarshal(resp.Data, &l); err != nil {
|
|
return nil, fmt.Errorf("json decode: %v", err)
|
|
}
|
|
|
|
return l.EntriesListItem, nil
|
|
}
|