From 3a272385626b6accfbb9a46b473ad1ff6e7642d3 Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Wed, 18 Aug 2021 11:40:34 +0200 Subject: [PATCH] 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. --- webhooks/context.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/webhooks/context.go b/webhooks/context.go index 638eaad763369e50bb0a3fe118f2fa5d756981cf..320878c37110f79137decac630051548d8fc54c9 100644 --- a/webhooks/context.go +++ b/webhooks/context.go @@ -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, ¶ms) + if errors != nil { + return fmt.Errorf("Error validating webhook query: %s", errors.Error()) + } + return nil +}