add basic query struct, support 1.12

This commit is contained in:
Ben Kraft
2019-12-23 19:35:38 -05:00
parent a23b0e3756
commit efa9ccd122
5 changed files with 65 additions and 10 deletions
+16
View File
@@ -0,0 +1,16 @@
package main
import (
"fmt"
"os"
"github.com/Khan/genql/generate"
)
func main() {
err := generate.Generate()
if err != nil {
fmt.Println(fmt.Errorf("genql failed: %v", err))
os.Exit(1)
}
}
+3 -2
View File
@@ -16,8 +16,8 @@ type GetViewerResponse = struct {
// GetViewer gets the current user's name.
func GetViewer(ctx context.Context) (*GetViewerResponse, error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodPost,
req, err := http.NewRequest(
http.MethodPost,
`https://api.github.com/graphql`,
strings.NewReader(`
"GetViewer gets the current user's name."
@@ -31,6 +31,7 @@ query GetViewer {
return nil, err
}
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
+2 -2
View File
@@ -1,6 +1,6 @@
"GetViewer gets the current user's name."
query GetUser($login: String!) {
User: user(login: $login) {
query GetViewer {
Viewer: viewer {
Name: name
}
}
+38 -1
View File
@@ -1,5 +1,42 @@
package generate
import "github.com/vektah/gqlparser"
import (
"fmt"
"os"
"text/template"
"github.com/vektah/gqlparser"
)
var _ = gqlparser.LoadSchema
// TODO: package template into the binary using one of those asset thingies
const tmplFilename = "generate/operation.go.tmpl"
type TemplateParams struct {
// The name of the package into which to generate the operation-helpers.
PackageName string
// The type-name for the operation's response type.
ResponseName string
// The body of the operation's response type (e.g. struct { ... }).
ResponseType string
// The documentation for the operation, from GraphQL.
OperationDoc string
// The name of the operation, from GraphQL.
OperationName string
// The endpoint to which to send queries.
Endpoint string
// The body of the operation to send.
Operation string
}
var tmpl = template.Must(template.ParseFiles(tmplFilename))
func Generate() error {
var data TemplateParams
err := tmpl.Execute(os.Stdout, data)
if err != nil {
return fmt.Errorf("template did not render: %v", err)
}
return nil
}
@@ -10,16 +10,17 @@ import (
type {{.ResponseName}} = {{.ResponseType}}
// {{.QueryDoc}}
func {{.QueryName}}(ctx context.Context) (*{{.ResponseName}}, error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodPost,
// {{.OperationDoc}}
func {{.OperationName}}(ctx context.Context) (*{{.ResponseName}}, error) {
req, err := http.NewRequest(
http.MethodPost,
`{{.Endpoint}}`,
strings.NewReader(`{{.Query}}`))
strings.NewReader(`{{.Operation}}`))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err