public void GlobalSetup()
    {
        var services = new ServiceCollection();

        services.AddSingleton <MyQueryGraphType>();
        services.AddSingleton <MyInputObjectGraphType>();
        services.AddSingleton <MySubInputObjectGraphType>();
        services.AddSingleton <ISchema, MySchema>();

        _provider = services.BuildServiceProvider();
        _schema   = _provider.GetRequiredService <ISchema>();
        _schema.Initialize();
        _executer             = new DocumentExecuter();
        _queryLiteralDocument = new Execution.GraphQLDocumentBuilder().Build(Queries.VariablesLiteral);

        _queryDefaultVariableDocument = new Execution.GraphQLDocumentBuilder().Build(Queries.VariablesDefaultVariable);

        _queryVariableDocument = new Execution.GraphQLDocumentBuilder().Build(Queries.VariablesVariable);
        _variableInputs        = new GraphQLSerializer().Deserialize <Inputs>(Variables.VariablesVariable);

        //confirm no errors during execution
        var val = EnableValidation;

        EnableValidation = true;
        Literal();
        DefaultVariable();
        Variable();
        EnableValidation = val;
    }
Exemple #2
0
        /// <summary>
        /// Analyzes the complexity of a document.
        /// </summary>
        internal ComplexityResult Analyze(GraphQLDocument doc, double avgImpact, int maxRecursionCount)
        {
            if (avgImpact <= 1)
            {
                throw new ArgumentOutOfRangeException(nameof(avgImpact));
            }

            var context = new AnalysisContext
            {
                MaxRecursionCount         = maxRecursionCount,
                AvgImpact                 = avgImpact,
                CurrentSubSelectionImpact = avgImpact,
                CurrentEndNodeImpact      = 1d
            };
            var visitor = new ComplexityVisitor();

            // https://github.com/graphql-dotnet/graphql-dotnet/issues/3030
            foreach (var frag in doc.Definitions.OfType <GraphQLFragmentDefinition>().OrderBy(x => x, new NestedFragmentsComparer(doc)))
            {
                visitor.VisitAsync(frag, context).GetAwaiter().GetResult();
            }

            context.FragmentMapAlreadyBuilt = true;

            visitor.VisitAsync(doc, context).GetAwaiter().GetResult();

            return(context.Result);
        }
        public IEnumerable<GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new VariablesInAllowedPositionsVisitor(schema);
            visitor.Visit(document);

            return visitor.Errors;
        }
Exemple #4
0
        public static GraphQLOperationDefinition GetOperation(GraphQLDocument document, string operationName)
        {
            var operations = document.Definitions.OfType <GraphQLOperationDefinition>().ToList();

            if (string.IsNullOrEmpty(operationName))
            {
                if (operations.Count == 1)
                {
                    return(operations.Single());
                }

                throw new DocumentException(
                          "Multiple operations found. Please provide OperationName");
            }

            var operation = operations.SingleOrDefault(op => op.Name.Value == operationName);

            if (operation == null)
            {
                throw new DocumentException(
                          $"Could not find operation with name {operationName}");
            }

            return(operation);
        }
Exemple #5
0
 private IValidationResult Validate(GraphQLDocument document) => _validator.ValidateAsync(
     new ValidationOptions
 {
     Schema    = _schema,
     Document  = document,
     Operation = document.Definitions.OfType <GraphQLOperationDefinition>().First()
 }).GetAwaiter().GetResult().validationResult;
Exemple #6
0
        public IDictionary <string, object> ExecuteQuery(string queryStr, TContext queryContext)
        {
            if (!_schema.Completed)
            {
                throw new InvalidOperationException("Schema must be Completed before executing a query. Try calling the schema's Complete method.");
            }

            if (queryContext == null)
            {
                throw new ArgumentException("Context must not be null.");
            }

            var document = GraphQLDocument <Info> .Parse(_schema.Adapter, queryStr);

            var context        = DefaultExecContext.Instance;  // TODO use a real IExecContext to support passing variables
            var operation      = document.Operations.Single(); // TODO support multiple operations per document, look up by name
            var execSelections = context.ToExecSelections(operation.Value);

            var outputs = new Dictionary <string, object>();

            foreach (var execSelection in execSelections.Select(s => s.Value))
            {
                var field = execSelection.SchemaField.Field();
                outputs[execSelection.Name] = Executor <TContext> .Execute(_schema, queryContext, field, execSelection);
            }
            return(outputs);
        }
Exemple #7
0
        public static SchemaBuilder Sdl(this SchemaBuilder builder, GraphQLDocument document)
        {
            var reader = new SdlReader(document, builder);

            reader.Read();
            return(builder);
        }
Exemple #8
0
 public ExecutionContext(GraphQLSchema graphQLSchema, GraphQLDocument ast)
 {
     this.graphQLSchema = graphQLSchema;
     this.ast           = ast;
     this.fragments     = new Dictionary <string, GraphQLFragmentDefinition>();
     this.variables     = new ExpandoObject();
 }
        /// <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);
        }
Exemple #10
0
        public virtual void Visit(GraphQLDocument ast)
        {
            if (ast.Definitions != null)
            {
                foreach (var definition in ast.Definitions)
                {
                    if (definition.Kind == ASTNodeKind.FragmentDefinition)
                    {
                        var    fragment = (GraphQLFragmentDefinition)definition;
                        string name     = fragment.Name?.Value;
                        if (name == null)
                        {
                            throw new InvalidOperationException("Fragment name cannot be null");
                        }

                        Fragments.Add(name, fragment);
                    }
                }

                foreach (var definition in ast.Definitions)
                {
                    BeginVisitNode(definition);
                }
            }
        }
 public async Task EndParseDocumentAsync(GraphQLDocument document)
 {
     foreach (var extension in _scopes)
     {
         await extension.EndParseDocumentAsync(document);
     }
 }
Exemple #12
0
        /// <summary>
        /// Converts an GraphQLParser AST representation of a document into a GraphQL.NET AST
        /// representation of a document and returns it.
        /// </summary>
        public static Document Convert(GraphQLDocument source)
        {
            var target = new Document();

            AddDefinitions(source, target);
            return(target);
        }
Exemple #13
0
 public virtual void Visit(GraphQLDocument ast)
 {
     foreach (var definition in ast.Definitions)
     {
         BeginVisitNode(definition);
     }
 }
Exemple #14
0
        private async Task RegisterSubscription(
            GraphQLFieldSelection fieldSelection,
            GraphQLSubscriptionType type,
            GraphQLDocument document,
            FieldScope scope)
        {
            var fieldInfo = type.GetFieldInfo(fieldSelection.Name.Value) as GraphQLSubscriptionTypeFieldInfo;

            Expression <Func <object, bool> > filter = null;

            if (fieldInfo.Filter != null)
            {
                filter = entity => (bool)scope.InvokeWithArgumentsSync(
                    fieldSelection.Arguments.ToList(), fieldInfo.Filter, entity);
            }

            await type.EventBus.Subscribe(EventBusSubscription.Create(
                                              fieldInfo.Channel,
                                              this.clientId,
                                              this.subscriptionId.Value,
                                              this.Operation?.Name?.Value ?? "Anonymous",
                                              this.variables,
                                              filter,
                                              this.ast));
        }
Exemple #15
0
        public T[] Search <T>(Func <ReqlExpr, ReqlExpr> searchFunction, GraphQLDocument document, UserContext.ReadType readType)
            where T : NodeBase
        {
            var type  = typeof(T[]);
            var table = GetTable(type);

            switch (readType)
            {
            case UserContext.ReadType.WithDocument:
                var selectionSet = GetSelectionSet(document);
                var hashMap      = GetHashMap(selectionSet, type);
                var importTree   = GetImportTree(typeof(T), hashMap, null);
                var docExpr      = searchFunction(table);
                docExpr = docExpr.Map(item => Merge(item, importTree));
                docExpr = docExpr.Map(item => item.Pluck(hashMap));
                var docResult = docExpr.CoerceTo("ARRAY").Run(_connection) as JArray;
                var docRet    = Utils.DeserializeObject(type, docResult);
                return(docRet as T[]);

            case UserContext.ReadType.Shallow:
                var shallowSearchExpr = searchFunction(table);
                var shallowResult     = shallowSearchExpr.CoerceTo("ARRAY").Run(_connection) as JArray;
                var shallowRet        = Utils.DeserializeObject(type, shallowResult);
                return(shallowRet as T[]);
            }

            return(null);
        }
Exemple #16
0
        internal bool Resolve(GraphQLDocument doc, IGraphQLFieldCollection rootType)
        {
            if (this.op.Name.Value == "__typename")
            {
                // special case here
                this.Type = Field.TypeName(doc);
            }
            else
            {
                // this is special we need to treat it as such
                this.Type = rootType.Fields.SingleOrDefault(x => x.Name == this.op.Name.Value);
                if (this.Type == null)
                {
                    doc.AddError(ErrorCodes.UnknownField, $"The field '{this.op.Name.Value}' in not a valid member of '{rootType.Name}'", this.op);
                    return(false);
                }
            }
            if (this.Selection != null)
            {
                IGraphQLType root = this.Type.Type.Type as IGraphQLType;

                var specifiedTypeName = doc.ResolveSpecifiedTypeName(this.op);
                this.Selection.Resolve(doc, root, specifiedTypeName);
            }

            //if (selection != null)
            //{
            //    // if we have subselction then it must be an object type really, unless an interface will work instead ???
            //    selection.Resolve(FieldType.Type.Type as IGraphQLFieldCollection);
            //}
            return(true);
        }
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new OverlappingFieldsCanBeMergedVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
Exemple #18
0
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new SingleFieldSubscriptionsVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
Exemple #19
0
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new UniqueDirectivesPerLocationVisitor();

            visitor.Visit(document);

            return(visitor.Errors);
        }
Exemple #20
0
        public override void Visit(GraphQLDocument document)
        {
            Tracker.EnterDocument?.Invoke(document);

            base.Visit(document);

            Tracker.LeaveDocument?.Invoke(document);
        }
Exemple #21
0
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new KnownFragmentNamesVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
        public static Document Convert(string body, GraphQLDocument source)
        {
            var converter = new CoreToVanillaConverter(body);
            var target    = new Document();

            converter.AddDefinitions(source, target);
            return(target);
        }
Exemple #23
0
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new LoneAnonymousOperationVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new NoUndefinedVariablesVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new UniqueArgumentsVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
        public IEnumerable <GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
        {
            var visitor = new FieldsOnCorrectTypeVisitor(schema);

            visitor.Visit(document);

            return(visitor.Errors);
        }
        public override void Visit(GraphQLDocument document)
        {
            this.operationCount = document.Definitions
                                  .Where(e => e.Kind == ASTNodeKind.OperationDefinition)
                                  .Count();

            base.Visit(document);
        }
Exemple #28
0
        private static GraphQLSelectionSet GetSelectionSet(GraphQLDocument document)
        {
            var operation =
                document.Definitions.First(d =>
                                           d.Kind == ASTNodeKind.OperationDefinition) as GraphQLOperationDefinition;
            var selectionSet = (operation?.SelectionSet?.Selections?.SingleOrDefault() as GraphQLFieldSelection)?.SelectionSet;

            return(selectionSet);
        }
Exemple #29
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);
        }
Exemple #30
0
        private static void Test()
        {
            var             parser     = new Parser(new Lexer());
            string          schemaJson = File.ReadAllText(@"E:\graphql.schema");
            var             source     = new Source(schemaJson);
            GraphQLDocument document   = parser.Parse(source);

            var querySource = new Source("query { orders (id: 1) { customer (address: \"rus\") { name } } }");
            var zzz         = parser.Parse(querySource);
        }