cic-chain-events/pkg/fetch/graphql.go

62 lines
1.3 KiB
Go
Raw Normal View History

2023-01-05 12:45:09 +01:00
package fetch
import (
"bytes"
"context"
2023-01-05 12:45:09 +01:00
"fmt"
"net/http"
"time"
"github.com/goccy/go-json"
2023-01-05 12:45:09 +01:00
)
const (
graphqlQuery = `{"query":"{block(number:%d){transactions{block{number,timestamp},hash,index,from{address},to{address},value,inputData,status,gasUsed}}}"}`
)
type GraphqlOpts struct {
GraphqlEndpoint string
}
type Graphql struct {
graphqlEndpoint string
httpClient *http.Client
}
func NewGraphqlFetcher(o GraphqlOpts) Fetch {
return &Graphql{
httpClient: &http.Client{
Timeout: time.Second * 2,
2023-01-05 12:45:09 +01:00
},
graphqlEndpoint: o.GraphqlEndpoint,
}
}
func (f *Graphql) Block(ctx context.Context, blockNumber uint64) (FetchResponse, error) {
2023-01-05 12:45:09 +01:00
var (
fetchResponse FetchResponse
)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.graphqlEndpoint, bytes.NewBufferString(fmt.Sprintf(graphqlQuery, blockNumber)))
2023-01-05 12:45:09 +01:00
if err != nil {
return FetchResponse{}, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := f.httpClient.Do(req)
if err != nil {
return FetchResponse{}, err
}
if resp.StatusCode >= http.StatusBadRequest {
2023-01-05 12:45:09 +01:00
return FetchResponse{}, fmt.Errorf("error fetching block %s", resp.Status)
}
2023-01-16 09:31:46 +01:00
defer resp.Body.Close()
2023-01-05 12:45:09 +01:00
2023-01-16 09:31:46 +01:00
if err := json.NewDecoder(resp.Body).Decode(&fetchResponse); err != nil {
2023-01-05 12:45:09 +01:00
return FetchResponse{}, err
}
return fetchResponse, nil
}