Exemplo n.º 1
0
        public void Create_InputObject_field()
        {
            /* Given */
            var builder = new SchemaBuilder();

            builder.InputObject(
                name: "Input1",
                out var input1);

            /* When */
            builder.Connections(connect => connect
                                .InputField(
                                    owner: input1,
                                    fieldName: "field1",
                                    to: ScalarType.NonNullBoolean,
                                    defaultValue: true,
                                    description: "Descriptipn",
                                    directives: new DirectiveInstance[]
            {
                /* directive */
            })
                                );


            /* Then */
            var isDefined = false;

            builder.Connections(connect => isDefined = connect.TryGetInputField(input1, "field1", out _));
            Assert.True(isDefined);
        }
        private InputObjectType InputObject(__Type type)
        {
            if (_builder.TryGetType <InputObjectType>(type.Name, out var owner))
            {
                return(owner);
            }

            _builder.InputObject(type.Name, out owner, type.Description);

            if (type.InputFields != null && type.InputFields.Any())
            {
                _builder.Connections(connect =>
                {
                    foreach (var field in type.InputFields)
                    {
                        connect.InputField(
                            owner,
                            field.Name,
                            InputType(field.Type),
                            field.DefaultValue,
                            field.Description);
                    }
                });
            }

            return(owner);
        }
Exemplo n.º 3
0
        protected IEnumerable <(string Name, IType Type, object DefaultValue, string Description)> Args(
            IEnumerable <GraphQLInputValueDefinition> definitions)
        {
            var args = new List <(string Name, IType Type, object DefaultValue, string Description)>();

            foreach (var definition in definitions)
            {
                var    type         = InputType(definition.Type);
                object defaultValue = null;

                try
                {
                    _builder.Connections(connections =>
                    {
                        defaultValue = Values.CoerceValue(
                            connections.GetInputFields,
                            definition.DefaultValue,
                            type);
                    });
                }
                catch (Exception)
                {
                    defaultValue = null;
                }

                args.Add((definition.Name.Value, type, defaultValue, default));
Exemplo n.º 4
0
        public static SchemaBuilder UseResolversAndSubscribers(
            this SchemaBuilder builder,
            IResolverMap resolvers,
            ISubscriberMap subscribers = null)
        {
            foreach (var type in builder.GetTypes <ObjectType>())
            {
                builder.Connections(connections =>
                {
                    foreach (var field in connections.GetFields(type))
                    {
                        var resolver = resolvers.GetResolver(type.Name, field.Key);

                        if (resolver != null)
                        {
                            connections.GetOrAddResolver(type, field.Key)
                            .Run(resolver);
                        }

                        var subscriber = subscribers?.GetSubscriber(type.Name, field.Key);

                        if (subscriber != null)
                        {
                            connections.GetOrAddSubscriber(type, field.Key)
                            .Run(subscriber);
                        }
                    }
                });
            }

            return(builder);
        }
Exemplo n.º 5
0
        private static void MergeInputType(ISchema right, SchemaBuilder builder, InputObjectType rightType)
        {
            if (builder.TryGetType <InputObjectType>(rightType.Name, out var leftType))
            {
                var rightTypeFields = right.GetInputFields(rightType.Name);

                foreach (var rightTypeField in rightTypeFields)
                {
                    builder.Connections(connect =>
                    {
                        if (connect.TryGetInputField(leftType, rightTypeField.Key, out _))
                        {
                            return;
                        }

                        connect.Include(leftType, new[] { rightTypeField });
                    });
                }
            }
            else
            {
                builder
                .Include(rightType)
                .Connections(connect =>
                {
                    var fields = right.GetInputFields(rightType.Name).ToList();
                    connect.Include(rightType, fields);
                });
            }
        }
Exemplo n.º 6
0
        public void Create_Object_field_when_type_not_known()
        {
            /* Given */
            var builder = new SchemaBuilder();
            var object1 = new ObjectType("Type");

            /* When */
            var exception = Assert.Throws <SchemaBuilderException>(() => builder.Connections(connect =>
            {
                connect.Field(
                    owner: object1,
                    fieldName: "field1",
                    to: ScalarType.Int,
                    description: "Description",
                    resolve: null,
                    subscribe: null,
                    directives: new DirectiveInstance[]
                {
                    /* directive */
                },
                    args => args.Arg(
                        name: "arg1",
                        type: ScalarType.Boolean,
                        defaultValue: true,
                        description: "Description")
                    );
            }));

            /* Then */
            Assert.Equal("Type", exception.TypeName);
        }
Exemplo n.º 7
0
        protected IEnumerable <(string Name, IType Type, object DefaultValue, string Description)> Args(
            IEnumerable <InputValueDefinition>?definitions)
        {
            var args = new List <(string Name, IType Type, object DefaultValue, string Description)>();

            if (definitions == null)
            {
                return(args);
            }

            foreach (var definition in definitions)
            {
                var    type         = InputType(definition.Type);
                object?defaultValue = null;

                try
                {
                    _builder.Connections(connections =>
                    {
                        defaultValue = Values.CoerceValue(
                            connections.GetInputFields,
                            _builder.GetValueConverter,
                            definition.DefaultValue?.Value,
                            type);
                    });
                }
                catch (Exception)
                {
                    defaultValue = null;
                }

                args.Add((definition.Name, type, defaultValue, default));
Exemplo n.º 8
0
        public void Create_Object_field()
        {
            /* Given */
            var builder = new SchemaBuilder();

            builder.Object(
                name: "Object1",
                out var object1);

            /* When */
            builder.Connections(connect =>
            {
                connect.Field(
                    owner: object1,
                    fieldName: "field1",
                    to: ScalarType.Int,
                    description: "Description",
                    resolve: null,
                    subscribe: null,
                    directives: new DirectiveInstance[]
                {
                    /* directive */
                },
                    args => args.Arg(
                        name: "arg1",
                        type: ScalarType.Boolean,
                        defaultValue: true,
                        description: "Description")
                    );
            });

            /* Then */
            var isDefined = false;

            builder.Connections(connect => isDefined = connect.TryGetField(object1, "field1", out _));
            Assert.True(isDefined);
        }
Exemplo n.º 9
0
        private static void MergeComplexTypeFields(ISchema right, SchemaBuilder builder, ComplexType rightType)
        {
            if (builder.TryGetType <ComplexType>(rightType.Name, out var leftType))
            {
                var rightTypeFields = right.GetFields(rightType.Name);

                foreach (var rightTypeField in rightTypeFields)
                {
                    builder.Connections(connect =>
                    {
                        // if field already exists skip it
                        if (connect.TryGetField(leftType, rightTypeField.Key, out _))
                        {
                            return;
                        }

                        // include field
                        connect.Include(leftType, rightTypeField);

                        // include resolver
                        var resolver = right.GetResolver(rightType.Name, rightTypeField.Key);

                        if (resolver != null)
                        {
                            connect.GetOrAddResolver(leftType, rightTypeField.Key)
                            .Run(resolver);
                        }

                        // include subscriber
                        var subscriber = right.GetSubscriber(rightType.Name, rightTypeField.Key);

                        if (subscriber != null)
                        {
                            connect.GetOrAddSubscriber(leftType, rightTypeField.Key)
                            .Run(subscriber);
                        }
                    });
                }
            }
            else
            {
                throw new SchemaBuilderException(
                          rightType.Name,
                          $"Cannot merge fields of {rightType}. Type is now known by builder. " +
                          $"Call MergeComplexType first.");
            }
        }
Exemplo n.º 10
0
        public async Task Part2_BindResolvers_Manual()
        {
            // Create builder and load sdl
            var builder = new SchemaBuilder()
                          .Sdl(@"
                type Query {
                    name: String
                }
                ");

            // Get query type
            builder.GetQuery(out var query);

            // Connections are used to defined fields and resolvers.
            // Connections method can be called multiple times.
            builder.Connections(connections =>
            {
                // Get or add resolver builder for Query.name field
                var nameResolverBuilder = connections
                                          .GetOrAddResolver(query, "name");

                // "Run" allows us to define an end of the resolver
                // chain. You can add "middlewares" using "Use".
                nameResolverBuilder
                .Run(context =>
                {
                    // Create result using Test as the value
                    var result = Resolve.As("Test");

                    // Resolvers can be sync or async so
                    // ValueTask result is used to reduce
                    // allocations
                    return(new ValueTask <IResolverResult>(result));
                });
            });

            // Build schema with the resolver
            var schema = builder.Build();

            // Get resolver for Query.name field
            var nameResolver = schema.GetResolver(schema.Query.Name, "name");

            // Execute the resolver. This is normally handled by the executor.
            var nameValue = await nameResolver(null);

            Assert.Equal("Test", nameValue.Value);
        }
Exemplo n.º 11
0
        public static SchemaBuilder Create()
        {
            var builder = new SchemaBuilder();

            var Episode = new EnumType("Episode", new EnumValues
            {
                ["NEWHOPE"] = null,
                ["EMPIRE"]  = null,
                ["JEDI"]    = null
            });

            builder.Include(Episode);

            var EpisodeList = new List(Episode);

            builder.Interface("Character", out var Character,
                              "Character in the movie");

            // use NamedTypeReference as proxy to bypass circular dependencies
            var CharacterList = new List(Character);

            builder.Connections(connect => connect
                                .Field(Character, "id", ScalarType.NonNullString)
                                .Field(Character, "name", ScalarType.NonNullString)
                                .Field(Character, "friends", CharacterList)
                                .Field(Character, "appearsIn", EpisodeList));

            builder.Object("Human", out var Human,
                           "Human character",
                           new[] { Character })
            .Connections(connect => connect
                         .Field(Human, "id", ScalarType.NonNullString)
                         .Field(Human, "name", ScalarType.NonNullString)
                         .Field(Human, "friends", CharacterList)
                         .Field(Human, "appearsIn", EpisodeList)
                         .Field(Human, "homePlanet", ScalarType.String));

            builder.Query(out var Query)
            .Connections(connect => connect
                         .Field(Query, "human", Human,
                                args: args => args.Arg("id", ScalarType.NonNullString, default, default))
Exemplo n.º 12
0
        public void Build_types()
        {
            /* Given */
            var builder = new SchemaBuilder();

            builder.Object("Object1", out var object1);
            builder.Query(out var query);

            builder.Connections(connect => connect
                                .Field(object1, "field1", ScalarType.Float)
                                .Field(query, "field1", object1));

            /* When */
            var sut = builder.Build();

            /* Then */
            var types = sut.QueryTypes <INamedType>();

            Assert.Contains(types, t => t.Name == "Query");
            Assert.Contains(types, t => t.Name == "Object1");
        }
Exemplo n.º 13
0
        public void Create_Interface_field()
        {
            /* Given */
            var builder = new SchemaBuilder();

            builder.Interface(
                name: "Interface1",
                out var interface1);

            /* When */
            builder.Connections(connect =>
            {
                connect.Field(
                    owner: interface1,
                    fieldName: "field1",
                    to: ScalarType.Int,
                    description: "Description",
                    resolve: null,
                    subscribe: null,
                    directives: new DirectiveInstance[]
                {
                    /* directive */
                },
                    (Name: "arg1",
                     Type: ScalarType.Boolean,
                     DefaultValue: true,
                     Description: "Description")
                    );
            });

            /* Then */
            var isDefined = false;

            builder.Connections(connect => isDefined = connect.TryGetField(interface1, "field1", out _));
            Assert.True(isDefined);
        }
Exemplo n.º 14
0
        public void Create_InputObject_field_when_type_not_known()
        {
            /* Given */
            var builder = new SchemaBuilder();
            var input1  = new InputObjectType("Type");

            /* When */
            var exception = Assert.Throws <SchemaBuilderException>(() => builder.Connections(connect => connect
                                                                                             .InputField(
                                                                                                 owner: input1,
                                                                                                 fieldName: "field1",
                                                                                                 to: ScalarType.NonNullBoolean,
                                                                                                 defaultValue: true,
                                                                                                 description: "Descriptipn",
                                                                                                 directives: new DirectiveInstance[]
            {
                /* directive */
            })
                                                                                             ));


            /* Then */
            Assert.Equal("Type", exception.TypeName);
        }
Exemplo n.º 15
0
        private static void MergeComplexType(ISchema right, SchemaBuilder builder, ComplexType rightType)
        {
            if (builder.TryGetType <ComplexType>(rightType.Name, out var leftType))
            {
                var rightTypeFields = right.GetFields(rightType.Name);

                foreach (var rightTypeField in rightTypeFields)
                {
                    builder.Connections(connect =>
                    {
                        if (connect.TryGetField(leftType, rightTypeField.Key, out _))
                        {
                            return;
                        }

                        connect.Include(leftType, new[] { rightTypeField });

                        var resolver = right.GetResolver(rightType.Name, rightTypeField.Key);

                        if (resolver != null)
                        {
                            connect.GetOrAddResolver(leftType, rightTypeField.Key)
                            .Run(resolver);
                        }

                        var subscriber = right.GetSubscriber(rightType.Name, rightTypeField.Key);

                        if (subscriber != null)
                        {
                            connect.GetOrAddSubscriber(leftType, rightTypeField.Key)
                            .Run(subscriber);
                        }
                    });
                }
            }
            else
            {
                builder
                .Include(rightType)
                .Connections(connect =>
                {
                    var fields = right.GetFields(rightType.Name).ToList();
                    connect.Include(rightType, fields);

                    foreach (var rightTypeField in fields)
                    {
                        var resolver = right.GetResolver(rightType.Name, rightTypeField.Key);

                        if (resolver != null)
                        {
                            connect.GetOrAddResolver(rightType, rightTypeField.Key)
                            .Run(resolver);
                        }

                        var subscriber = right.GetSubscriber(rightType.Name, rightTypeField.Key);

                        if (subscriber != null)
                        {
                            connect.GetOrAddSubscriber(rightType, rightTypeField.Key)
                            .Run(subscriber);
                        }
                    }
                });
            }
        }
Exemplo n.º 16
0
        public static ISchema MakeRemoteExecutable(
            SchemaBuilder builder,
            ExecutionResultLink link,
            Func <ExecutionResultLink, Resolver> createResolver     = null,
            Func <ExecutionResultLink, Subscriber> createSubscriber = null)
        {
            if (createResolver == null)
            {
                createResolver = DefaultCreateRemoteResolver;
            }

            if (createSubscriber == null)
            {
                createSubscriber = DefaultCreateRemoteSubscriber;
            }

            // add remote resolver for query
            if (builder.TryGetType <ObjectType>("Query", out var queryType))
            {
                builder.Connections(connections =>
                {
                    var fields = connections.VisitFields(queryType);

                    foreach (var field in fields)
                    {
                        var resolver = connections.GetOrAddResolver(queryType, field.Key);
                        resolver.Run(createResolver(link));
                    }
                });
            }

            if (builder.TryGetType <ObjectType>("Mutation", out var mutationType))
            {
                builder.Connections(connections =>
                {
                    var fields = connections.VisitFields(mutationType);

                    foreach (var field in fields)
                    {
                        var resolver = connections.GetOrAddResolver(mutationType, field.Key);
                        resolver.Run(createResolver(link));
                    }
                });
            }

            if (builder.TryGetType <ObjectType>("Subscription", out var subscriptionType))
            {
                builder.Connections(connections =>
                {
                    var fields = connections.VisitFields(subscriptionType);

                    foreach (var field in fields)
                    {
                        if (!connections.TryGetSubscriber(subscriptionType, field.Key, out _))
                        {
                            var subscriber = connections.GetOrAddSubscriber(subscriptionType, field.Key);
                            subscriber.Run(createSubscriber(link));
                        }
                    }
                });
            }

            foreach (var objectType in builder.VisitTypes <ObjectType>())
            {
                builder.Connections(connections =>
                {
                    foreach (var field in connections.VisitFields(objectType))
                    {
                        if (!connections.TrGetResolver(objectType, field.Key, out _))
                        {
                            var resolver = connections.GetOrAddResolver(objectType, field.Key);
                            resolver.Run(DefaultDictionaryResolver());
                        }
                    }
                });
            }

            return(builder.Build());
        }
Exemplo n.º 17
0
        public static SchemaBuilder ApplyDirectives(
            this SchemaBuilder builder,
            IReadOnlyDictionary <string, CreateDirectiveVisitor> directiveFactories)
        {
            if (directiveFactories == null)
            {
                throw new ArgumentNullException(nameof(directiveFactories));
            }

            foreach (var(directiveName, visitor) in directiveFactories.Select(d => (d.Key, d.Value(builder))))
            {
                foreach (var objectType in builder.GetTypes <ObjectType>())
                {
                    builder.Connections(connections =>
                    {
                        var fields = connections.GetFields(objectType)
                                     .Where(field => field.Value.HasDirective(directiveName))
                                     .ToList();

                        foreach (var field in fields)
                        {
                            var directive = field.Value.GetDirective(directiveName);

                            if (visitor.FieldDefinition == null)
                            {
                                continue;
                            }

                            var resolver        = connections.GetOrAddResolver(objectType, field.Key)?.Build();
                            var subscriber      = connections.GetOrAddSubscriber(objectType, field.Key)?.Build();
                            var fieldDefinition = new DirectiveFieldVisitorContext(
                                field.Key,
                                field.Value,
                                resolver,
                                subscriber);

                            var maybeSameField = visitor.FieldDefinition(directive, fieldDefinition);

                            // field not modified
                            if (maybeSameField == fieldDefinition)
                            {
                                continue;
                            }

                            // field removed
                            if (maybeSameField == null)
                            {
                                connections.Remove(objectType, field.Key);
                                continue;
                            }

                            // changed so remove and add
                            connections.Remove(objectType, field.Key);
                            connections.Include(objectType, new[]
                            {
                                new KeyValuePair <string, IField>(maybeSameField.Name, maybeSameField.Field)
                            });
                            connections.Include(objectType, maybeSameField.Name,
                                                new ResolverBuilder(maybeSameField.Resolver));
                            connections.Include(objectType, maybeSameField.Name,
                                                new SubscriberBuilder(maybeSameField.Subscriber));
                        }
                    });
                }
            }

            return(builder);
        }