Пример #1
0
        private string PrintOperationDefinition(GraphQLOperationDefinition definition)
        {
            var name         = PrintName(definition.Name);
            var directives   = Join(definition.Directives?.Select(this.PrintDirective), " ");
            var selectionSet = this.PrintSelectionSet(definition.SelectionSet);

            var variableDefinitions = Wrap(
                "(",
                this.Join(definition.VariableDefinitions?.Select(this.PrintVariableDefinition), ", "), ")");

            var operation = definition.Operation
                            .ToString()
                            .ToLower();

            var variables = string.IsNullOrWhiteSpace(name) ? variableDefinitions : this.Join(new[] { name, variableDefinitions });

            return(this.Join(
                       new[]
            {
                operation,
                variables,
                directives,
                selectionSet
            },
                       " "));
        }
Пример #2
0
 internal static void Operation(this ILogger logger, GraphQLOperationDefinition operation)
 {
     OperationAction(
         logger,
         operation.Operation.ToString().ToLowerInvariant(),
         operation.Name?.Value, null);
 }
Пример #3
0
        private static async Task <ExecutionResult> ExecuteSubscriptionEventAsync(
            IExecutorContext context,
            GraphQLOperationDefinition subscription,
            Dictionary <string, object> coercedVariableValues,
            object evnt,
            Func <Exception, Error> formatError)
        {
            var subscriptionType = context.Schema.Subscription;
            var selectionSet     = subscription.SelectionSet;
            var path             = new NodePath();
            var data             = await SelectionSets.ExecuteSelectionSetAsync(
                context,
                selectionSet,
                subscriptionType,
                evnt,
                coercedVariableValues,
                path).ConfigureAwait(false);

            var result = new ExecutionResult
            {
                Errors = context.FieldErrors.Select(formatError).ToList(),
                Data   = data
            };

            return(result);
        }
Пример #4
0
        public static IReadOnlyDictionary <string, object> CoerceVariableValues(
            ISchema schema,
            GraphQLOperationDefinition operation,
            Dictionary <string, object> variableValues)
        {
            var coercedValues       = new Dictionary <string, object>();
            var variableDefinitions = operation.VariableDefinitions;

            if (variableDefinitions == null)
            {
                return(coercedValues);
            }

            foreach (var variableDefinition in variableDefinitions)
            {
                var variableName = variableDefinition.Variable.Name.Value;
                var variableType = Ast.TypeFromAst(schema, variableDefinition.Type);

                //  should be assert?
                if (!TypeIs.IsInputType(variableType))
                {
                    throw new VariableException($"Variable is not of input type", variableName, variableType);
                }

                var defaultValue = variableDefinition.DefaultValue;
                var hasValue     = variableValues.ContainsKey(variableName);
                var value        = variableValues[variableName];

                if (!hasValue && defaultValue != null)
                {
                    coercedValues[variableName] = defaultValue;
                }

                if (variableType is NonNull &&
                    (!hasValue || value == null))
                {
                    throw new ValueCoercionException(
                              $"Variable {variableName} type is non-nullable but value is null or not set",
                              value,
                              variableType);
                }

                if (hasValue)
                {
                    if (value == null)
                    {
                        coercedValues[variableName] = null;
                    }
                    else
                    {
                        coercedValues[variableName] = Values.CoerceValue(
                            schema.GetInputFields,
                            value,
                            variableType);
                    }
                }
            }

            return(coercedValues);
        }
        /// <summary>
        /// Builds a <see cref="ExecutionContext"/> instance from the provided values.
        /// </summary>
        protected virtual ExecutionContext BuildExecutionContext(ExecutionOptions options, GraphQLDocument document, GraphQLOperationDefinition operation, Variables variables, Metrics metrics)
        {
            var context = new ExecutionContext
            {
                Document    = document,
                Schema      = options.Schema !,
                RootValue   = options.Root,
                UserContext = options.UserContext,

                Operation         = operation,
                Variables         = variables,
                Errors            = new ExecutionErrors(),
                InputExtensions   = options.Extensions ?? Inputs.Empty,
                OutputExtensions  = new Dictionary <string, object?>(),
                CancellationToken = options.CancellationToken,

                Metrics   = metrics,
                Listeners = options.Listeners,
                ThrowOnUnhandledException  = options.ThrowOnUnhandledException,
                UnhandledExceptionDelegate = options.UnhandledExceptionDelegate,
                MaxParallelExecutionCount  = options.MaxParallelExecutionCount,
                RequestServices            = options.RequestServices,
            };

            context.ExecutionStrategy = SelectExecutionStrategy(context);

            return(context);
        }
Пример #6
0
    private bool ShouldBeSkipped(GraphQLOperationDefinition actualOperation, ValidationContext context)
    {
        if (context.Document.OperationsCount() <= 1)
        {
            return(false);
        }

        int i = 0;

        do
        {
            var ancestor = context.TypeInfo.GetAncestor(i++);

            if (ancestor == actualOperation)
            {
                return(false);
            }

            if (ancestor == context.Document)
            {
                return(true);
            }

            if (ancestor is GraphQLFragmentDefinition fragment)
            {
                //TODO: may be rewritten completely later
                var c = new FragmentBelongsToOperationVisitorContext(fragment);
                _visitor.VisitAsync(actualOperation, c).GetAwaiter().GetResult(); // TODO: need to think of something to avoid this
                return(!c.Found);
            }
        } while (true);
    }
Пример #7
0
        public async Task <ExpandoObject> ComposeResultForSubscriptions(
            GraphQLComplexType type, GraphQLOperationDefinition operationDefinition)
        {
            if (string.IsNullOrWhiteSpace(this.clientId))
            {
                throw new GraphQLException(
                          "Can't invoke subscription without clientId specified",
                          new ASTNode[] { operationDefinition });
            }

            if (!this.subscriptionId.HasValue)
            {
                throw new GraphQLException(
                          "Can't invoke subscription without subscriptionId specified",
                          new ASTNode[] { operationDefinition });
            }

            var context = this.CreateExecutionContext(operationDefinition);

            var scope = new FieldScope(context, type, null);

            return(await this.ProcessSubscription(
                       (GraphQLSubscriptionType)type,
                       context.FieldCollector,
                       scope));
        }
Пример #8
0
        private string PrintOperationDefinition(GraphQLOperationDefinition definition)
        {
            var name         = PrintName(definition.Name);
            var directives   = Join(definition.Directives?.Select(PrintDirective), " ");
            var selectionSet = PrintSelectionSet(definition.SelectionSet);

            var variableDefinitions = Wrap(
                "(",
                Join(definition.VariableDefinitions?.Select(PrintVariableDefinition), ", "), ")");

            var operation = definition.Operation
                            .ToString()
                            .ToLower();

            return(string.IsNullOrWhiteSpace(name) &&
                   string.IsNullOrWhiteSpace(name) &&
                   string.IsNullOrWhiteSpace(name) &&
                   definition.Operation == OperationType.Query
                ? selectionSet
                : Join(
                       new[]
            {
                operation,
                Join(new[] { name, variableDefinitions }),
                directives,
                selectionSet
            },
                       " "));
        }
Пример #9
0
        public Operation(GraphQLOperationDefinition op)
        {
            this.operation = op;

            Name = op.Name?.Value;

            Selection = new SetSelection(operation.SelectionSet);
        }
Пример #10
0
        public static IEnumerable <VariableUsage> Get(
            GraphQLOperationDefinition operation, GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new VariableUsagesProvider(GetFragmentsFromDocument(document), schema);

            visitor.BeginVisitOperationDefinition(operation);

            return(visitor.variableUsages);
        }
Пример #11
0
        public override GraphQLOperationDefinition BeginVisitOperationDefinition(
            GraphQLOperationDefinition definition)
        {
            {
                Tracker.EnterOperationDefinition?.Invoke(definition);
            }

            return(base.BeginVisitOperationDefinition(definition));
        }
        public override GraphQLOperationDefinition BeginVisitOperationDefinition(GraphQLOperationDefinition definition)
        {
            if (definition.Name == null && this.operationCount > 1)
            {
                this.Errors.Add(new GraphQLException("This anonymous operation must be the only defined operation.", new[] { definition }));
            }

            return(definition);
        }
Пример #13
0
        public override GraphQLOperationDefinition EndVisitOperationDefinition(
            GraphQLOperationDefinition definition)
        {
            {
                Tracker.LeaveOperationDefinition?.Invoke(definition);
            }

            return(base.EndVisitOperationDefinition(definition));
        }
        private void VerifyUsage(GraphQLOperationDefinition operation, VariableUsage usage, string opName)
        {
            var variableName = usage.Variable.Name.Value;

            if (!this.variableDefinitions.Contains(variableName))
            {
                this.Errors.Add(new GraphQLException(this.ComposeUndefinedVarMessage(variableName, opName),
                                                     new ASTNode[] { usage.Variable, operation }));
            }
        }
Пример #15
0
 public void Deconstruct(out ISchema schema, out GraphQLDocument document,
                         out GraphQLOperationDefinition operation, out object initialValue,
                         out Dictionary <string, object> coercedVariableValues)
 {
     schema                = Schema;
     document              = Document;
     operation             = OperationDefinition;
     initialValue          = InitialValue;
     coercedVariableValues = CoercedVariableValues;
 }
Пример #16
0
        public virtual GraphQLOperationDefinition BeginVisitOperationDefinition(GraphQLOperationDefinition definition)
        {
            if (definition.Name != null)
            {
                this.BeginVisitNode(definition.Name);
            }

            this.BeginVisitNode(definition.SelectionSet);
            return(definition);
        }
Пример #17
0
 private static Operation Operation(GraphQLOperationDefinition source)
 {
     return(new Operation(Name(source.Name), SelectionSet(source.SelectionSet))
     {
         SourceLocation = Convert(source.Location),
         CommentNode = Comment(source.Comment),
         OperationType = ToOperationType(source.Operation),
         Variables = VariableDefinitions(source.VariableDefinitions),
         Directives = Directives(source.Directives)
     });
 }
        public override GraphQLOperationDefinition EndVisitOperationDefinition(GraphQLOperationDefinition definition)
        {
            var variableUsages = VariableUsagesProvider.Get(definition, this.document, this.Schema);

            foreach (var usage in variableUsages)
            {
                this.VerifyUsage(usage);
            }

            return(base.EndVisitOperationDefinition(definition));
        }
        public Operation Operation(GraphQLOperationDefinition source)
        {
            var name = source.Name != null?Name(source.Name) : null;

            var op = new Operation(name).WithLocation(source, _body);

            op.OperationType = ToOperationType(source.Operation);
            op.SelectionSet  = SelectionSet(source.SelectionSet);
            op.Variables     = VariableDefinitions(source.VariableDefinitions);
            op.Directives    = Directives(source.Directives);
            return(op);
        }
Пример #20
0
        private void ResolveOperationDefinition(GraphQLOperationDefinition graphQLOperationDefinition)
        {
            if (this.operation != null)
            {
                throw new Exception("Must provide operation name if query contains multiple operations.");
            }

            if (this.operation == null)
            {
                this.operation = graphQLOperationDefinition;
            }
        }
        public override GraphQLOperationDefinition BeginVisitOperationDefinition(GraphQLOperationDefinition definition)
        {
            if (definition.Operation == OperationType.Subscription)
            {
                if (definition.SelectionSet?.Selections?.Count() != 1)
                {
                    this.Errors.Add(new GraphQLException(
                                        this.SingleFieldOnlyMessage(definition.Name?.Value),
                                        definition.SelectionSet.Selections.Skip(1).ToArray()));
                }
            }

            return(definition);
        }
 public BenchmarkInfo(string query, string inputs, Func <ISchema> schemaBuilder)
 {
     // this exercises all the code in case of any errors, in addition to prep for each stage of testing
     SchemaBuilder   = schemaBuilder;
     Schema          = BuildSchema();
     Query           = query;
     Document        = Parse();
     Operation       = Document.Definitions.OfType <GraphQLOperationDefinition>().FirstOrDefault();
     InputsString    = inputs;
     Inputs          = DeserializeInputs();
     Variables       = ParseVariables();
     ExecutionResult = Execute();
     _ = Serialize();
 }
        public override GraphQLOperationDefinition BeginVisitOperationDefinition(GraphQLOperationDefinition definition)
        {
            switch (definition.Operation)
            {
            case OperationType.Query: this.typeStack.Push(this.Schema.QueryType); break;

            default: throw new NotImplementedException();
            }

            definition = base.BeginVisitOperationDefinition(definition);
            this.typeStack.Pop();

            return(definition);
        }
Пример #24
0
 public virtual GraphQLOperationDefinition BeginVisitOperationDefinition(
     GraphQLOperationDefinition definition)
 {
     if (definition.Name != null)
     {
         BeginVisitNode(definition.Name);
     }
     if (definition.VariableDefinitions != null)
     {
         BeginVisitVariableDefinitions(definition.VariableDefinitions);
     }
     BeginVisitNode(definition.SelectionSet);
     return(EndVisitOperationDefinition(definition));
 }
        public ExecutionResult Execute()
        {
            var context = new Execution.ExecutionContext
            {
                Document    = Document,
                Schema      = Schema,
                RootValue   = null,
                UserContext = new Dictionary <string, object>(),

                Operation         = Operation,
                Variables         = Variables,
                Errors            = new ExecutionErrors(),
                InputExtensions   = Inputs.Empty,
                OutputExtensions  = new Dictionary <string, object>(),
                CancellationToken = default,
Пример #26
0
        private void ResolveOperationDefinition(GraphQLOperationDefinition graphQLOperationDefinition, string operationToExecute)
        {
            if (this.Operation != null && string.IsNullOrWhiteSpace(operationToExecute))
            {
                throw new GraphQLException("Must provide operation name if query contains multiple operations.");
            }

            if (!string.IsNullOrWhiteSpace(operationToExecute) && graphQLOperationDefinition.Name.Value == operationToExecute)
            {
                this.Operation = graphQLOperationDefinition;
            }
            else if (string.IsNullOrWhiteSpace(operationToExecute) && this.Operation == null)
            {
                this.Operation = graphQLOperationDefinition;
            }
        }
Пример #27
0
        private ExecutionContext CreateExecutionContext(GraphQLOperationDefinition operationDefinition)
        {
            var variableResolver = this.CreateVariableResolver();

            var fieldCollector = new FieldCollector(
                this.fragments,
                this.graphQLSchema.SchemaRepository);

            return(new ExecutionContext()
            {
                FieldCollector = fieldCollector,
                OperationType = operationDefinition.Operation,
                Schema = this.graphQLSchema,
                SchemaRepository = this.graphQLSchema.SchemaRepository,
                VariableResolver = variableResolver
            });
        }
        public override GraphQLOperationDefinition EndVisitOperationDefinition(GraphQLOperationDefinition definition)
        {
            var variableUsages = VariableUsagesProvider.Get(definition, this.document, this.Schema);
            var operationName  = definition.Name != null ? definition.Name.Value : null;

            foreach (var variableDefinition in this.variableDefinitions)
            {
                var variableName = variableDefinition.Variable.Name.Value;
                if (!variableUsages.Any(e => e.Variable.Name.Value == variableName))
                {
                    this.Errors.Add(new GraphQLException(this.GetUnusedVariablesMessage(variableName, operationName),
                                                         new[] { variableDefinition }));
                }
            }

            return(base.EndVisitOperationDefinition(definition));
        }
Пример #29
0
 public ExecutorContext(ISchema schema,
                        GraphQLDocument document,
                        ExtensionsRunner extensionsRunner,
                        IExecutionStrategy strategy,
                        GraphQLOperationDefinition operation,
                        IDictionary <string, GraphQLFragmentDefinition> fragments,
                        IReadOnlyDictionary <string, object> coercedVariableValues)
 {
     Schema                = schema ?? throw new ArgumentNullException(nameof(schema));
     Document              = document ?? throw new ArgumentNullException(nameof(document));
     ExtensionsRunner      = extensionsRunner ?? throw new ArgumentNullException(nameof(extensionsRunner));
     Strategy              = strategy ?? throw new ArgumentNullException(nameof(strategy));
     Operation             = operation;
     Fragments             = fragments;
     CoercedVariableValues = coercedVariableValues;
     _errors               = new List <Exception>();
 }
Пример #30
0
 public QueryContext(
     Func <Exception, Error> formatError,
     GraphQLDocument document,
     GraphQLOperationDefinition operation,
     ISchema schema,
     Dictionary <string, object> coercedVariableValues,
     object initialValue,
     Extensions extensions)
 {
     FormatError         = formatError ?? throw new ArgumentNullException(nameof(formatError));
     Document            = document ?? throw new ArgumentNullException(nameof(document));
     OperationDefinition = operation ?? throw new ArgumentNullException(nameof(operation));
     Schema = schema ?? throw new ArgumentNullException(nameof(schema));
     CoercedVariableValues =
         coercedVariableValues ?? throw new ArgumentNullException(nameof(coercedVariableValues));
     InitialValue = initialValue;
     Extensions   = extensions;
 }