~bigbes/core-go

3a272385626b6accfbb9a46b473ad1ff6e7642d3 — Drew DeVault 5 years ago f500157
webhooks: add query validation function

The new function tests a query against a GraphQL schema and returns any
validation errors if they are found. This is useful for determining if a
GraphQL query will pass validation when creating a new webhook.
1 files changed, 22 insertions(+), 0 deletions(-)

M webhooks/context.go
M webhooks/context.go => webhooks/context.go +22 -0
@@ 5,6 5,7 @@ import (
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"

	"github.com/99designs/gqlgen/graphql"
	"github.com/99designs/gqlgen/graphql/executor"


@@ 84,3 85,24 @@ func (webhook *WebhookContext) Exec(ctx context.Context,
	}
	return payload, nil
}

// Validates the given query against the provided schema and returns any errors
// should they be found, or nil if the query passes validation.
func Validate(schema graphql.ExecutableSchema, query string) error {
	// XXX: We would create less garbage if we ran the validator ourselves
	// instead of letting gqlgen do it for us via CreateOperationContext
	exec := executor.New(schema)
	params := graphql.RawParams{
		Query: query,
		ReadTime: graphql.TraceTiming{
			Start: graphql.Now(),
			End:   graphql.Now(),
		},
	}
	ctx := graphql.StartOperationTrace(context.TODO())
	_, errors := exec.CreateOperationContext(ctx, &params)
	if errors != nil {
		return fmt.Errorf("Error validating webhook query: %s", errors.Error())
	}
	return nil
}