github.com/dgraph-io/dgraph@v1.2.8/graphql/schema/request.go (about) 1 /* 2 * Copyright 2019 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package schema 18 19 import ( 20 "github.com/pkg/errors" 21 22 "github.com/vektah/gqlparser/ast" 23 "github.com/vektah/gqlparser/parser" 24 "github.com/vektah/gqlparser/validator" 25 ) 26 27 // A Request represents a GraphQL request. It makes no guarantees that the 28 // request is valid. 29 type Request struct { 30 Query string `json:"query"` 31 OperationName string `json:"operationName"` 32 Variables map[string]interface{} `json:"variables"` 33 } 34 35 // Operation finds the operation in req, if it is a valid request for GraphQL 36 // schema s. If the request is GraphQL valid, it must contain a single valid 37 // Operation. If either the request is malformed or doesn't contain a valid 38 // operation, all GraphQL errors encountered are returned. 39 func (s *schema) Operation(req *Request) (Operation, error) { 40 if req == nil || req.Query == "" { 41 return nil, errors.New("no query string supplied in request") 42 } 43 44 doc, gqlErr := parser.ParseQuery(&ast.Source{Input: req.Query}) 45 if gqlErr != nil { 46 return nil, gqlErr 47 } 48 49 listErr := validator.Validate(s.schema, doc) 50 if len(listErr) != 0 { 51 return nil, listErr 52 } 53 54 if len(doc.Operations) > 1 && req.OperationName == "" { 55 return nil, errors.Errorf("Operation name must by supplied when query has more " + 56 "than 1 operation.") 57 } 58 59 op := doc.Operations.ForName(req.OperationName) 60 if op == nil { 61 return nil, errors.Errorf("Supplied operation name %s isn't present in the request.", 62 req.OperationName) 63 } 64 65 vars, gqlErr := validator.VariableValues(s.schema, op, req.Variables) 66 if gqlErr != nil { 67 return nil, gqlErr 68 } 69 70 return &operation{op: op, 71 vars: vars, 72 query: req.Query, 73 doc: doc, 74 inSchema: s, 75 }, nil 76 }