68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package openstates
|
|
|
|
import (
|
|
"context"
|
|
"reflect"
|
|
|
|
"github.com/machinebox/graphql"
|
|
)
|
|
|
|
type OpenStatesApi struct {
|
|
ApiKey string
|
|
Client *graphql.Client
|
|
}
|
|
|
|
func NewOpenStatesApi(key string) *OpenStatesApi {
|
|
o := OpenStatesApi{
|
|
ApiKey: key,
|
|
}
|
|
o.Client = graphql.NewClient("https://openstates.org/graphql")
|
|
return &o
|
|
}
|
|
|
|
func (o *OpenStatesApi) SetLogger(l func(s string)) {
|
|
o.Client.Log = l
|
|
}
|
|
|
|
func (o *OpenStatesApi) MakeQueryRequest(query string, vars map[string]interface{}, res interface{}) error {
|
|
req := graphql.NewRequest(query)
|
|
for k, v := range vars {
|
|
req.Var(k, v)
|
|
}
|
|
return o.MakeRawRequest(req, &res)
|
|
}
|
|
|
|
func (o *OpenStatesApi) MakeRequest(res interface{}, vars map[string]interface{}) error {
|
|
req := o.buildRequest(res, vars)
|
|
return o.MakeRawRequest(req, res)
|
|
}
|
|
|
|
func (o *OpenStatesApi) MakeRawRequest(req *graphql.Request, res interface{}) error {
|
|
ctx := context.Background()
|
|
req.Header.Add("X-API-KEY", o.ApiKey)
|
|
return o.Client.Run(ctx, req, &res)
|
|
}
|
|
|
|
func (o *OpenStatesApi) buildRequest(res interface{}, vars map[string]interface{}) *graphql.Request {
|
|
// TODO: Build query from res
|
|
req := graphql.NewRequest(`query Reps($lat:Float,$long:Float){people(latitude:$lat,longitude:$long,first:100){edges{node{id name sortName familyName givenName image birthDate deathDate createdAt updatedAt extras }}}}`)
|
|
for k, v := range vars {
|
|
req.Var(k, v)
|
|
}
|
|
return req
|
|
}
|
|
|
|
func GetFields(in interface{}) []string {
|
|
var ret []string
|
|
val := reflect.ValueOf(in)
|
|
for i := 0; i < val.Type().NumField(); i++ {
|
|
t := val.Type().Field(i)
|
|
fieldName := t.Name
|
|
if jsonTag := t.Tag.Get("json"); jsonTag != "" && jsonTag != "-" {
|
|
fieldName = jsonTag
|
|
}
|
|
ret = append(ret, fieldName)
|
|
}
|
|
return ret
|
|
}
|