Esempio n. 1
0
        public void Build(ISchema schema)
        {
            var inventoryQueryField = new FieldType
            {
                Name      = "inventory",
                Arguments = new QueryArguments(new QueryArgument <NonNullGraphType <StringGraphType> > {
                    Name = "id", Description = "id of the inventory"
                }),
                Type     = typeof(InventoryType),
                Resolver = new AsyncFieldResolver <Inventory>(context =>
                {
                    return(Task.FromResult(new Inventory {
                        ProductId = "1", FulfillmentCenterId = "center1"
                    }));
                })
            };

            schema.Query.AddField(inventoryQueryField);


            var saveInventoryField = FieldBuilder.Create <Inventory, Inventory>(typeof(InventoryType))
                                     .Name("saveInventory")
                                     .Argument <NonNullGraphType <InputUpdateInventoryType> >("inventory")
                                     .Resolve(context =>
            {
                var inventory = context.GetArgument <Inventory>("inventory");
                //TODO: Insert mutation logic here
                return(inventory);
            }).FieldType;

            schema.Mutation.AddField(saveInventoryField);
        }
        /// <summary>
        /// Adds a new field to the complex graph type and returns a builder for this newly added field that is linked to a property of the source object.
        /// <br/><br/>
        /// Note: this method uses dynamic compilation and therefore allocates a relatively large amount of
        /// memory in managed heap, ~1KB. Do not use this method in cases with limited memory requirements.
        /// </summary>
        /// <typeparam name="TProperty">The return type of the field.</typeparam>
        /// <param name="name">The name of this field.</param>
        /// <param name="expression">The property of the source object represented within an expression.</param>
        /// <param name="nullable">Indicates if this field should be nullable or not. Ignored when <paramref name="type"/> is specified.</param>
        /// <param name="type">The graph type of the field; if <see langword="null"/> then will be inferred from the specified expression via registered schema mappings.</param>
        public virtual FieldBuilder <TSourceType, TProperty> Field <TProperty>(
            string name,
            Expression <Func <TSourceType, TProperty> > expression,
            bool nullable = false,
            Type?type     = null)
        {
            try
            {
                if (type == null)
                {
                    type = typeof(TProperty).GetGraphTypeFromType(nullable, this is IInputObjectGraphType ? TypeMappingMode.InputType : TypeMappingMode.OutputType);
                }
            }
            catch (ArgumentOutOfRangeException exp)
            {
                throw new ArgumentException($"The GraphQL type for field '{Name ?? GetType().Name}.{name}' could not be derived implicitly from expression '{expression}'.", exp);
            }

            var builder = FieldBuilder.Create <TSourceType, TProperty>(type)
                          .Name(name)
                          .Resolve(new ExpressionFieldResolver <TSourceType, TProperty>(expression))
                          .Description(expression.DescriptionOf())
                          .DeprecationReason(expression.DeprecationReasonOf())
                          .DefaultValue(expression.DefaultValueOf());

            if (expression.Body is MemberExpression expr)
            {
                builder.FieldType.Metadata[ORIGINAL_EXPRESSION_PROPERTY_NAME] = expr.Member.Name;
            }

            AddField(builder.FieldType);
            return(builder);
        }
Esempio n. 3
0
        private static Builders.FieldBuilder <IDictionary <string, object>, TReturn> EfFieldFromContext <TDbContext, TSource, TReturn>(this IEfGraph <TDbContext, TSource> graph, string name, Func <ResolveEfFieldContext <TDbContext, TSource>, LambdaExpression> expression, bool nullable = false, Type graphType = null) where TDbContext : DbContext where TSource : class
        {
            //obtain the type
            try
            {
                if (graphType == null)
                {
                    graphType = typeof(TReturn).GetGraphTypeFromType(nullable);
                }
            }
            catch (ArgumentOutOfRangeException exp)
            {
                throw new ArgumentException(
                          $"The GraphQL type for Field: '{name}' on parent type: '{graph.Name ?? graph.GetType().Name}' could not be derived implicitly. \n",
                          exp
                          );
            }

            var builder = FieldBuilder.Create <IDictionary <string, object>, TReturn>(graphType)
                          .Name(name)
                          .Resolve(EfGraphResolver)
                          //.Description(expression.DescriptionOf())
                          //.DeprecationReason(expression.DeprecationReasonOf())
                          //.DefaultValue(expression.DefaultValueOf())
            ;

            builder.FieldType.SetExpressionMetadata <TDbContext, TSource>(expression);
            graph.AddField(builder.FieldType);
            return(builder);
        }
Esempio n. 4
0
        public FieldBuilder <TSourceType, object> Field <TGraphType>()
        {
            var builder = FieldBuilder.Create <TSourceType, object>(typeof(TGraphType));

            AddField(builder.FieldType);
            return(builder);
        }
Esempio n. 5
0
        public FieldBuilder <TSourceType, TProperty> Field <TProperty>(
            string name,
            Expression <Func <TSourceType, TProperty> > expression,
            bool nullable = false,
            Type type     = null)
        {
            try
            {
                if (type == null)
                {
                    type = typeof(TProperty).GetGraphTypeFromType(nullable);
                }
            }
            catch (ArgumentOutOfRangeException exp)
            {
                throw new ArgumentException(
                          $"The GraphQL type for Field: '{name}' on parent type: '{Name ?? GetType().Name}' could not be derived implicitly. \n",
                          exp
                          );
            }

            var builder = FieldBuilder.Create <TSourceType, TProperty>(type)
                          .Resolve(new ExpressionFieldResolver <TSourceType, TProperty>(expression))
                          .Name(name);

            AddField(builder.FieldType);
            return(builder);
        }
Esempio n. 6
0
        public FieldBuilder <TGraphType, object, TGraphType> Field <TGraphType>()
            where TGraphType : GraphType
        {
            var builder = FieldBuilder.Create <TGraphType>();

            _fields.Add(builder.FieldType);
            return(builder);
        }
        /// <summary>
        /// Adds a new field to the complex graph type and returns a builder for this newly added field.
        /// </summary>
        /// <typeparam name="TGraphType">The graph type of the field.</typeparam>
        /// <typeparam name="TReturnType">The return type of the field resolver.</typeparam>
        /// <param name="name">The name of the field.</param>
        public virtual FieldBuilder <TSourceType, TReturnType> Field <TGraphType, TReturnType>(string name = "default")
        {
            var builder = FieldBuilder.Create <TSourceType, TReturnType>(typeof(TGraphType))
                          .Name(name);

            AddField(builder.FieldType);
            return(builder);
        }
Esempio n. 8
0
        public void Create_name_for_enumerable_primitives_test()
        {
            var ctx    = new TestBuildContext();
            var output = FieldBuilder.Create(typeof(int[]), "test", ctx);

            output.CreateNames();
            output.CreateNames();

            ctx.Names.Count.Should().BeGreaterOrEqualTo(1);
            ctx.Names.Keys.Should().Contain("_value");
        }
Esempio n. 9
0
        public void Create_name_for_primitives_test()
        {
            var ctx    = new TestBuildContext();
            var output = FieldBuilder.Create(typeof(int), "test", ctx);

            output.CreateNames();
            output.CreateNames();

            ctx.Names.Count.Should().Be(1);
            ctx.Names.Keys.Should().Contain("test");
        }
Esempio n. 10
0
        public void Create_name_for_complex_test()
        {
            var ctx    = new TestBuildContext();
            var output = FieldBuilder.Create(typeof(TestEntity), "test", ctx);

            output.CreateNames();
            output.CreateNames();

            ctx.Names.Count.Should().BeGreaterOrEqualTo(7);
            ctx.Names.Keys.Should().Contain("test_Age");
            ctx.Names.Keys.Should().Contain("test_Address_City");
            ctx.Names.Keys.Should().Contain("_value");
        }
Esempio n. 11
0
        public void Set_value_for_primitive_test()
        {
            var ctx    = new TestBuildContext();
            var output = FieldBuilder.Create(typeof(string), "test", ctx);

            output.CreateNames();

            output.SetValue("test value");
            ctx.Names["test"].Should().Be("test value");

            output.SetValue(2);
            ctx.Names["test"].Should().Be(2);
        }
Esempio n. 12
0
        public FieldBuilder <TSourceType, TProperty> Field <TProperty>(
            string name,
            Expression <Func <TSourceType, TProperty> > expression,
            bool nullable = false,
            Type type     = null)
        {
            type = type ?? typeof(TProperty).GetGraphTypeFromType(nullable);

            var builder = FieldBuilder.Create <TSourceType, TProperty>(type)
                          .Resolve(new ExpressionFieldResolver <TSourceType, TProperty>(expression))
                          .Name(name);

            AddField(builder.FieldType);
            return(builder);
        }
Esempio n. 13
0
        public void Set_value_for_complex_test()
        {
            var ctx    = new TestBuildContext();
            var output = FieldBuilder.Create(typeof(TestEntity), "test", ctx);

            output.CreateNames();

            output.SetValue(new TestEntity("test name", "test role", 36, new [] { 23, 42 })
            {
                Address = new Address("RUS", "SPB", "Nevskiy")
            });
            ctx.Names["test_Name"].Should().Be("test name");
            ctx.Names["test_Role"].Should().Be("test role");
            ctx.Names["test_Age"].Should().Be(36);
            ctx.Names["test_Address_City"].Should().Be("SPB");
        }
Esempio n. 14
0
 public FieldBuilder Field(string type, string name) => FieldBuilder.Create(this, type, name);
Esempio n. 15
0
        public void Passing_enumerable_primitive_should_create_HorizontalRangeBuilder()
        {
            var output = FieldBuilder.Create(typeof(DateTime[]), "test", new TestBuildContext());

            output.Should().BeOfType <HorizontalRangeBuilder>();
        }
Esempio n. 16
0
        public void Passing_enumerable_complex_should_create_VerticalRangeBuilder()
        {
            var output = FieldBuilder.Create(typeof(Address[]), "test", new TestBuildContext());

            output.Should().BeOfType <VerticalRangeBuilder>();
        }
Esempio n. 17
0
        public void Passing_complex_should_create_ComplexFieldBuilder(object value)
        {
            var output = FieldBuilder.Create(value.GetType(), "test", new TestBuildContext());

            output.Should().BeOfType <ComplexFieldBuilder>();
        }
Esempio n. 18
0
        public void Build(ISchema schema)
        {
            _ = schema.Query.AddField(new FieldType
            {
                Name      = "order",
                Arguments = new QueryArguments(
                    new QueryArgument <StringGraphType> {
                    Name = "id"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "number"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "cultureName", Description = "Culture name (\"en-US\")"
                }),
                Type     = GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var request = new GetOrderQuery
                    {
                        Number      = context.GetArgument <string>("number"),
                        OrderId     = context.GetArgument <string>("id"),
                        CultureName = context.GetArgument <string>(nameof(Currency.CultureName))
                    };

                    var orderAggregate = await _mediator.Send(request);

                    var authorizationResult = await _authorizationService.AuthorizeAsync(context.GetCurrentPrincipal(), orderAggregate.Order, new CanAccessOrderAuthorizationRequirement());

                    if (!authorizationResult.Succeeded)
                    {
                        throw new ExecutionError($"Access denied");
                    }

                    var allCurrencies = await _currencyService.GetAllCurrenciesAsync();
                    //Store all currencies in the user context for future resolve in the schema types
                    context.SetCurrencies(allCurrencies, request.CultureName);

                    //store order aggregate in the user context for future usage in the graph types resolvers
                    context.SetExpandedObjectGraph(orderAggregate);

                    return(orderAggregate);
                })
            });

            var orderConnectionBuilder = GraphTypeExtenstionHelper.CreateConnection <CustomerOrderType, object>()
                                         .Name("orders")
                                         .Argument <StringGraphType>("filter", "This parameter applies a filter to the query results")
                                         .Argument <StringGraphType>("sort", "The sort expression")
                                         .Argument <StringGraphType>("cultureName", "Culture name (\"en-US\")")
                                         .Argument <StringGraphType>("userId", "")
                                         .Unidirectional()
                                         .PageSize(20);

            orderConnectionBuilder.ResolveAsync(async context => await ResolveOrdersConnectionAsync(_mediator, context));

            schema.Query.AddField(orderConnectionBuilder.FieldType);


            var paymentsConnectionBuilder = GraphTypeExtenstionHelper.CreateConnection <PaymentInType, object>()
                                            .Name("payments")
                                            .Argument <StringGraphType>("filter", "This parameter applies a filter to the query results")
                                            .Argument <StringGraphType>("sort", "The sort expression")
                                            .Argument <StringGraphType>("cultureName", "Culture name (\"en-US\")")
                                            .Argument <NonNullGraphType <StringGraphType> >("userId", "")
                                            .Unidirectional()
                                            .PageSize(20);

            paymentsConnectionBuilder.ResolveAsync(async context => await ResolvePaymentsConnectionAsync(_mediator, context));
            schema.Query.AddField(paymentsConnectionBuilder.FieldType);


            _ = schema.Mutation.AddField(FieldBuilder.Create <object, CustomerOrderAggregate>(typeof(CustomerOrderType))
                                         .Name("createOrderFromCart")
                                         .Argument <NonNullGraphType <InputCreateOrderFromCartType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var response = await _mediator.Send(context.GetArgument <CreateOrderFromCartCommand>(_commandName));
                context.SetExpandedObjectGraph(response);
                return(response);
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, bool>(typeof(BooleanGraphType))
                                         .Name("changeOrderStatus")
                                         .Argument <NonNullGraphType <InputChangeOrderStatusType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <ChangeOrderStatusCommand>(_commandName);

                var order = await _customerOrderService.GetByIdAsync(command.OrderId);

                var authorizationResult = await _authorizationService.AuthorizeAsync(context.GetCurrentPrincipal(), order, new CanAccessOrderAuthorizationRequirement());

                if (!authorizationResult.Succeeded)
                {
                    throw new ExecutionError($"Access denied");
                }

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, bool>(typeof(BooleanGraphType))
                                         .Name("confirmOrderPayment")
                                         .Argument <NonNullGraphType <InputConfirmOrderPaymentType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <ConfirmOrderPaymentCommand>(_commandName);
                var order   = await _customerOrderService.GetByIdAsync(command.Payment.OrderId);

                var authorizationResult = await _authorizationService.AuthorizeAsync(context.GetCurrentPrincipal(), order, new CanAccessOrderAuthorizationRequirement());

                if (!authorizationResult.Succeeded)
                {
                    throw new ExecutionError($"Access denied");
                }

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, bool>(typeof(BooleanGraphType))
                                         .Name("cancelOrderPayment")
                                         .Argument <NonNullGraphType <InputCancelOrderPaymentType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <CancelOrderPaymentCommand>(_commandName);
                var order   = await _customerOrderService.GetByIdAsync(command.Payment.OrderId);

                var authorizationResult = await _authorizationService.AuthorizeAsync(context.GetCurrentPrincipal(), order, new CanAccessOrderAuthorizationRequirement());

                if (!authorizationResult.Succeeded)
                {
                    throw new ExecutionError($"Access denied");
                }

                return(await _mediator.Send(command));
            })
                                         .FieldType);
        }
        public void Build(ISchema schema)
        {
            //Queries
            //We can't use the fluent syntax for new types registration provided by dotnet graphql here, because we have the strict requirement for underlying types extensions
            //and must use GraphTypeExtenstionHelper to resolve the effective type on execution time
            var cartField = new FieldType
            {
                Name      = "cart",
                Arguments = new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                    Name = "storeId", Description = "Store Id"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "userId", Description = "User Id"
                },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                    Name = "currencyCode", Description = "Currency code (\"USD\")"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "cultureName", Description = "Culture name (\"en-Us\")"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "cartName", Description = "Cart name"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "type", Description = "Cart type"
                }),
                Type     = GraphTypeExtenstionHelper.GetActualType <CartType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var getCartQuery           = context.GetCartQuery <GetCartQuery>();
                    getCartQuery.IncludeFields = context.SubFields.Values.GetAllNodesPaths().ToArray();
                    context.CopyArgumentsToUserContext();
                    var cartAggregate = await _mediator.Send(getCartQuery);
                    if (cartAggregate == null)
                    {
                        var createCartCommand = new CreateCartCommand(getCartQuery.StoreId, getCartQuery.CartType, getCartQuery.CartName, getCartQuery.UserId, getCartQuery.CurrencyCode, getCartQuery.CultureName);
                        cartAggregate         = await _mediator.Send(createCartCommand);
                    }

                    context.SetExpandedObjectGraph(cartAggregate);

                    return(cartAggregate);
                })
            };

            schema.Query.AddField(cartField);


            var orderConnectionBuilder = GraphTypeExtenstionHelper.CreateConnection <CartType, object>()
                                         .Name("carts")
                                         .Argument <StringGraphType>("storeId", "")
                                         .Argument <StringGraphType>("userId", "")
                                         .Argument <StringGraphType>("currencyCode", "")
                                         .Argument <StringGraphType>("cultureName", "")
                                         .Argument <StringGraphType>("cartType", "")
                                         .Argument <StringGraphType>("filter", "This parameter applies a filter to the query results")
                                         .Argument <StringGraphType>("sort", "The sort expression")
                                         .Unidirectional()
                                         .PageSize(20);

            orderConnectionBuilder.ResolveAsync(async context => await ResolveConnectionAsync(_mediator, context));

            schema.Query.AddField(orderConnectionBuilder.FieldType);

            //Mutations
            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputAddItemType!){ addItem(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "productId": "9cbd8f316e254a679ba34a900fccb076",
            ///          "quantity": 1
            ///      }
            ///   }
            /// }
            /// </example>
            var addItemField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                               .Name("addItem")
                               .Argument <NonNullGraphType <InputAddItemType> >(_commandName)
                               //TODO: Write the unit-tests for successfully mapping input variable to the command
                               .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <AddCartItemCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            })
                               .FieldType;

            schema.Mutation.AddField(addItemField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputClearCartType!){ clearCart(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart"
            ///      }
            ///   }
            /// }
            /// </example>
            var clearCartField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                 .Name("clearCart")
                                 .Argument <NonNullGraphType <InputClearCartType> >(_commandName)
                                 .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <ClearCartCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(clearCartField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputChangeCommentType!){ changeComment(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "comment": "Hi, Virto!"
            ///      }
            ///   }
            /// }
            /// </example>
            var changeCommentField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                     .Name("changeComment")
                                     .Argument <InputChangeCommentType>(_commandName)
                                     .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <ChangeCommentCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            })
                                     .FieldType;

            schema.Mutation.AddField(changeCommentField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputChangeCartItemPriceType!){ changeCartItemPrice(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "lineItemId": "9cbd8f316e254a679ba34a900fccb076",
            ///          "price": 777
            ///      }
            ///   }
            /// }
            /// </example>
            var changeCartItemPriceField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                           .Name("changeCartItemPrice")
                                           .Argument <NonNullGraphType <InputChangeCartItemPriceType> >(_commandName)
                                           .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <ChangeCartItemPriceCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(changeCartItemPriceField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputChangeCartItemQuantityType!){ changeCartItemQuantity(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "lineItemId": "9cbd8f316e254a679ba34a900fccb076",
            ///          "quantity": 777
            ///      }
            ///   }
            /// }
            /// </example>
            var changeCartItemQuantityField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                              .Name("changeCartItemQuantity")
                                              .Argument <NonNullGraphType <InputChangeCartItemQuantityType> >(_commandName)
                                              .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <ChangeCartItemQuantityCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(changeCartItemQuantityField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputChangeCartItemCommentType!){ changeCartItemComment(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "lineItemId": "9cbd8f316e254a679ba34a900fccb076",
            ///          "comment": "verynicecomment"
            ///      }
            ///   }
            /// }
            /// </example>
            var changeCartItemCommentField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                             .Name("changeCartItemComment")
                                             .Argument <InputChangeCartItemCommentType>(_commandName)
                                             .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <ChangeCartItemCommentCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(changeCartItemCommentField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputRemoveItemType!){ removeCartItem(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "lineItemId": "9cbd8f316e254a679ba34a900fccb076"
            ///      }
            ///   }
            /// }
            /// </example>
            var removeCartItemField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                      .Name("removeCartItem")
                                      .Argument <NonNullGraphType <InputRemoveItemType> >(_commandName)
                                      .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <RemoveCartItemCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(removeCartItemField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputAddCouponType!){ addCoupon(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "couponCode": "verynicecouponcode"
            ///      }
            ///   }
            /// }
            /// </example>
            var addCouponField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                 .Name("addCoupon")
                                 .Argument <NonNullGraphType <InputAddCouponType> >(_commandName)
                                 .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <AddCouponCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(addCouponField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputRemoveCouponType!){ removeCoupon(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "couponCode": "verynicecouponcode"
            ///      }
            ///   }
            /// }
            /// </example>
            var removeCouponField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                    .Name("removeCoupon")
                                    .Argument <NonNullGraphType <InputRemoveCouponType> >(_commandName)
                                    .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <RemoveCouponCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(removeCouponField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputRemoveShipmentType!){ removeShipment(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "shipmentId": "7777-7777-7777-7777"
            ///      }
            ///   }
            /// }
            /// </example>
            var removeShipmentField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                      .Name("removeShipment")
                                      .Argument <NonNullGraphType <InputRemoveShipmentType> >(_commandName)
                                      .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <RemoveShipmentCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(removeShipmentField);

            //TODO: add shipment model to example
            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputAddOrUpdateCartShipmentType!){ addOrUpdateCartShipment(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "shipment": { }
            ///      }
            ///   }
            /// }
            /// </example>
            var addOrUpdateCartShipmentField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                               .Name("addOrUpdateCartShipment")
                                               .Argument <NonNullGraphType <InputAddOrUpdateCartShipmentType> >(_commandName)
                                               .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <AddOrUpdateCartShipmentCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(addOrUpdateCartShipmentField);

            //TODO: add payment model to example
            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputAddOrUpdateCartPaymentType!){ addOrUpdateCartPayment(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "payment": { }
            ///      }
            ///   }
            /// }
            /// </example>
            var addOrUpdateCartPaymentField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                              .Name("addOrUpdateCartPayment")
                                              .Argument <NonNullGraphType <InputAddOrUpdateCartPaymentType> >(_commandName)
                                              .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <AddOrUpdateCartPaymentCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(addOrUpdateCartPaymentField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputValidateCouponType!){ validateCoupon(command: $command) }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "coupon": {
            ///             "code":"verynicecodeforvalidation"
            ///         }
            ///      }
            ///   }
            /// }
            /// </example>
            var validateCouponField = FieldBuilder.Create <CartAggregate, bool>(typeof(BooleanGraphType))
                                      .Name("validateCoupon")
                                      .Argument <NonNullGraphType <InputValidateCouponType> >(_commandName)
                                      .ResolveAsync(async context => await _mediator.Send(context.GetArgument <ValidateCouponCommand>(_commandName)))
                                      .FieldType;

            schema.Mutation.AddField(validateCouponField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:MergeCartType!){ mergeCart(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "secondCartId": "7777-7777-7777-7777"
            ///      }
            ///   }
            /// }
            /// </example>
            var margeCartField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                 .Name("mergeCart")
                                 .Argument <NonNullGraphType <InputMergeCartType> >(_commandName)
                                 .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetCartCommand <MergeCartCommand>());
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            }).FieldType;

            schema.Mutation.AddField(margeCartField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputRemoveCartType!){ removeCart(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "cartId": "7777-7777-7777-7777"
            ///      }
            ///   }
            /// }
            /// </example>
            var removeCartField = FieldBuilder.Create <CartAggregate, bool>(typeof(BooleanGraphType))
                                  .Name("removeCart")
                                  .Argument <NonNullGraphType <InputRemoveCartType> >(_commandName)
                                  .ResolveAsync(async context => await _mediator.Send(context.GetArgument <RemoveCartCommand>(_commandName)))
                                  .FieldType;

            schema.Mutation.AddField(removeCartField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputClearShipmentsType!){ clearShipments(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "cartId": "7777-7777-7777-7777"
            ///      }
            ///   }
            /// }
            /// </example>
            var clearShipmentsField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                      .Name("clearShipments")
                                      .Argument <NonNullGraphType <InputClearShipmentsType> >(_commandName)
                                      .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetArgument <ClearShipmentsCommand>(_commandName));
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            })
                                      .FieldType;

            schema.Mutation.AddField(clearShipmentsField);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputClearPaymentsType!){ clearPayments(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "cartId": "7777-7777-7777-7777"
            ///      }
            ///   }
            /// }
            /// </example>
            var clearPaymentsField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                     .Name("clearPayments")
                                     .Argument <NonNullGraphType <InputClearPaymentsType> >(_commandName)
                                     .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetArgument <ClearPaymentsCommand>(_commandName));
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            })
                                     .FieldType;

            schema.Mutation.AddField(clearPaymentsField);


            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputAddOrUpdateCartAddressType!){ addOrUpdateCartAddress(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "storeId": "Electronics",
            ///          "cartName": "default",
            ///          "userId": "b57d06db-1638-4d37-9734-fd01a9bc59aa",
            ///          "language": "en-US",
            ///          "currency": "USD",
            ///          "cartType": "cart",
            ///          "address": {
            ///             "line1":"st street 1"
            ///         }
            ///      }
            ///   }
            /// }
            /// </example>
            var addOrUpdateCartAddress = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                         .Name("addOrUpdateCartAddress")
                                         .Argument <NonNullGraphType <InputAddOrUpdateCartAddressType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                //TODO: Need to refactor later to prevent ugly code duplication
                //We need to add cartAggregate to the context to be able use it on nested cart types resolvers (e.g for currency)
                var cartAggregate = await _mediator.Send(context.GetArgument <AddOrUpdateCartAddressCommand>(_commandName));
                //store cart aggregate in the user context for future usage in the graph types resolvers
                context.SetExpandedObjectGraph(cartAggregate);
                return(cartAggregate);
            })
                                         .FieldType;

            schema.Mutation.AddField(addOrUpdateCartAddress);

            /// <example>
            /// This is an example JSON request for a mutation
            /// {
            ///   "query": "mutation ($command:InputRemoveCartAddressType!){ removeCartAddress(command: $command) {  total { formatedAmount } } }",
            ///   "variables": {
            ///      "command": {
            ///          "cartId": "7777-7777-7777-7777",
            ///          "addressId": "111"
            ///      }
            ///   }
            /// }
            /// </example>
            var removeCartAddressField = FieldBuilder.Create <CartAggregate, CartAggregate>(typeof(CartType))
                                         .Name("removeCartAddress")
                                         .Argument <NonNullGraphType <InputRemoveCartAddressType> >(_commandName)
                                         .ResolveAsync(async context => await _mediator.Send(context.GetArgument <RemoveCartAddressCommand>(_commandName)))
                                         .FieldType;

            schema.Mutation.AddField(removeCartAddressField);
        }
Esempio n. 20
0
        public void Build(ISchema schema)
        {
            ValueConverter.Register <ExpOrderAddress, Optional <ExpOrderAddress> >(x => new Optional <ExpOrderAddress>(x));

            _ = schema.Query.AddField(new FieldType
            {
                Name      = "order",
                Arguments = AbstractTypeFactory <OrderQueryArguments> .TryCreateInstance(),
                Type      = GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>(),
                Resolver  = new AsyncFieldResolver <object>(async context =>
                {
                    var request = context.ExtractQuery <GetOrderQuery>();

                    context.CopyArgumentsToUserContext();
                    var orderAggregate = await _mediator.Send(request);

                    var authorizationResult = await _authorizationService.AuthorizeAsync(context.GetCurrentPrincipal(), orderAggregate.Order, new CanAccessOrderAuthorizationRequirement());

                    if (!authorizationResult.Succeeded)
                    {
                        throw new AuthorizationError($"Access denied");
                    }

                    var allCurrencies = await _currencyService.GetAllCurrenciesAsync();
                    //Store all currencies in the user context for future resolve in the schema types
                    context.SetCurrencies(allCurrencies, request.CultureName);

                    //store order aggregate in the user context for future usage in the graph types resolvers
                    context.SetExpandedObjectGraph(orderAggregate);

                    return(orderAggregate);
                })
            });

            var orderConnectionBuilder = GraphTypeExtenstionHelper
                                         .CreateConnection <CustomerOrderType, object>()
                                         .Name("orders")
                                         .PageSize(20)
                                         .Arguments();

            orderConnectionBuilder.ResolveAsync(async context => await ResolveOrdersConnectionAsync(_mediator, context));
            schema.Query.AddField(orderConnectionBuilder.FieldType);

            var paymentsConnectionBuilder = GraphTypeExtenstionHelper
                                            .CreateConnection <PaymentInType, object>()
                                            .Name("payments")
                                            .PageSize(20)
                                            .Arguments();

            paymentsConnectionBuilder.ResolveAsync(async context => await ResolvePaymentsConnectionAsync(_mediator, context));
            schema.Query.AddField(paymentsConnectionBuilder.FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("createOrderFromCart")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputCreateOrderFromCartType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type     = GenericTypeHelper.GetActualType <CreateOrderFromCartCommand>();
                var response = (CustomerOrderAggregate)await _mediator.Send(context.GetArgument(type, _commandName));
                context.SetExpandedObjectGraph(response);
                return(response);
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, bool>(typeof(BooleanGraphType))
                                         .Name("changeOrderStatus")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputChangeOrderStatusType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <ChangeOrderStatusCommand>();
                var command = (ChangeOrderStatusCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, ProcessPaymentRequestResult>(typeof(ProcessPaymentRequestResultType))
                                         .Name("processOrderPayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputProcessOrderPaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <ProcessOrderPaymentCommand>();
                var command = (ProcessOrderPaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .DeprecationReason("Obsolete. Use 'initializePayment' mutation")
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, InitializePaymentResult>(typeof(InitializePaymentResultType))
                                         .Name("initializePayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputInitializePaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type = GenericTypeHelper.GetActualType <InitializePaymentCommand>();

                var command = (InitializePaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, AuthorizePaymentResult>(typeof(AuthorizePaymentResultType))
                                         .Name("authorizePayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputAuthorizePaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type = GenericTypeHelper.GetActualType <AuthorizePaymentCommand>();

                var command = (AuthorizePaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);


            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderDynamicPropertiesCommand>();
                var command = (UpdateOrderDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderItemDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderItemDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderItemDynamicPropertiesCommand>();
                var command = (UpdateOrderItemDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderPaymentDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderPaymentDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderPaymentDynamicPropertiesCommand>();
                var command = (UpdateOrderPaymentDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderShipmentDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderShipmentDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderShipmentDynamicPropertiesCommand>();
                var command = (UpdateOrderShipmentDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("addOrUpdateOrderPayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputAddOrUpdateOrderPaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <AddOrUpdateOrderPaymentCommand>();
                var command = (AddOrUpdateOrderPaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                var response = await _mediator.Send(command);

                context.SetExpandedObjectGraph(response);

                return(response);
            })
                                         .FieldType);
        }
Esempio n. 21
0
        public void Passing_primitive_should_create_PrimitiveFieldBuilder(object value)
        {
            var output = FieldBuilder.Create(value.GetType(), "test", new TestBuildContext());

            output.Should().BeOfType <PrimitiveFieldBuilder>();
        }
        public void Build(ISchema schema)
        {
            schema.Query.AddField(new FieldType
            {
                Name     = "me",
                Type     = GraphTypeExtenstionHelper.GetActualType <UserType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var userName = ((GraphQLUserContext)context.UserContext).User?.Identity.Name;
                    if (!string.IsNullOrEmpty(userName))
                    {
                        var result = await _mediator.Send(new GetUserQuery
                        {
                            UserName = userName
                        });
                        return(result);
                    }
                    return(AnonymousUser.Instance);
                })
            });

            //Queries

            #region organization query

            /* organization query with contacts connection filtering:
             * {
             * organization(id: "689a72757c754bef97cde51afc663430"){
             *   id contacts(first:10, after: "0", searchPhrase: null){
             *    totalCount items {id firstName}
             *  }
             * }
             * }
             */

            #endregion
            schema.Query.AddField(new FieldType
            {
                Name      = "organization",
                Arguments = new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                    Name = "id"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "userId"
                }
                    ),
                Type     = GraphTypeExtenstionHelper.GetActualType <OrganizationType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var organizationId        = context.GetArgument <string>("id");
                    var query                 = new GetOrganizationByIdQuery(organizationId);
                    var organizationAggregate = await _mediator.Send(query);

                    await CheckAuthAsync(context.GetCurrentUserId(), organizationAggregate);
                    //store organization aggregate in the user context for future usage in the graph types resolvers
                    context.UserContext.Add("organizationAggregate", organizationAggregate);

                    return(organizationAggregate);
                })
            });

            #region contact query
            /// <example>
#pragma warning disable S125 // Sections of code should not be commented out

            /*
             *           {
             *            contact(id: "51311ae5-371c-453b-9394-e6d352f1cea7"){
             *                firstName memberType organizationIds organizations { id businessCategory description emails groups memberType name outerId ownerId parentId phones seoObjectType }
             *                addresses { line1 phone }
             *           }
             *          }
             */
#pragma warning restore S125 // Sections of code should not be commented out
            /// </example>

            #endregion
            schema.Query.AddField(new FieldType
            {
                Name      = "contact",
                Arguments = new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                    Name = "id"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "userId"
                }
                    ),
                Type     = GraphTypeExtenstionHelper.GetActualType <ContactType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var query            = new GetContactByIdQuery(context.GetArgument <string>("id"));
                    var contactAggregate = await _mediator.Send(query);
                    await CheckAuthAsync(context.GetCurrentUserId(), contactAggregate);
                    //store organization aggregate in the user context for future usage in the graph types resolvers
                    context.UserContext.Add("contactAggregate", contactAggregate);

                    return(contactAggregate);
                })
            });

            #region updateAddressMutation

            /// sample code for updating addresses:
#pragma warning disable S125 // Sections of code should not be commented out

            /*
             *          mutation updateAddresses($command: InputUpdateContactAddressType!){
             *          contact: updateAddresses(command: $command)
             *            {
             *              firstName lastName
             *              addresses { key city countryCode countryName email firstName  lastName line1 line2 middleName name phone postalCode regionId regionName zip }
             *            }
             *          }
             *          query variables:
             *          {
             *              "command": {
             *                "contactId": "acc3b262-a21e-45f9-a612-b4b1530d27ef",
             *                "addresses": [{"addressType": "Shipping", "name": "string", "countryCode": "string", "countryName": "string", "city": "string", "postalCode": "string", "line1": "string", "regionId": "string", "regionName": "string", "firstName": "string", "lastName": "string", "phone": "string", "email": "string", "regionId": "string"
             *                  }]
             *              }
             *          }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Mutation.AddField(FieldBuilder.Create <ContactAggregate, ContactAggregate>(typeof(ContactType))
                                         .Name("updateAddresses")
                                         .Argument <NonNullGraphType <InputUpdateContactAddressType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <UpdateContactAddressesCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);
                return(await _mediator.Send(command));
            })
                                         .FieldType);


            _ = schema.Mutation.AddField(FieldBuilder.Create <OrganizationAggregate, OrganizationAggregate>(typeof(OrganizationType))
                                         .Name("updateOrganization")
                                         .Argument <NonNullGraphType <InputUpdateOrganizationType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <UpdateOrganizationCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command, CustomerModule.Core.ModuleConstants.Security.Permissions.Update);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <OrganizationAggregate, OrganizationAggregate>(typeof(OrganizationType))
                                         .Name("createOrganization")
                                         .Argument <NonNullGraphType <InputCreateOrganizationType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <CreateOrganizationCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <ContactAggregate, ContactAggregate>(typeof(ContactType))
                                         .Name("createContact")
                                         .Argument <NonNullGraphType <InputCreateContactType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <CreateContactCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <ContactAggregate, ContactAggregate>(typeof(ContactType))
                                         .Name("updateContact")
                                         .Argument <NonNullGraphType <InputUpdateContactType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <UpdateContactCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <ContactAggregate, bool>(typeof(BooleanGraphType))
                                         .Name("deleteContact")
                                         .Argument <NonNullGraphType <InputDeleteContactType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <DeleteContactCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command, CustomerModule.Core.ModuleConstants.Security.Permissions.Delete);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, IdentityResult>(typeof(IdentityResultType))
                                         .Name("updatePersonalData")
                                         .Argument <NonNullGraphType <InputUpdatePersonalDataType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <UpdatePersonalDataCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            // Security API fields

            #region user query

#pragma warning disable S125 // Sections of code should not be commented out

            /*
             *              {
             *                  user(id: "1eb2fa8ac6574541afdb525833dadb46"){
             *                  userName isAdministrator roles { name } userType memberId storeId
             *                  }
             *              }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Query.AddField(new FieldType
            {
                Name      = "user",
                Arguments = new QueryArguments(
                    new QueryArgument <StringGraphType> {
                    Name = "id"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "userName"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "email"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "loginProvider"
                },
                    new QueryArgument <StringGraphType> {
                    Name = "providerKey"
                }),
                Type     = GraphTypeExtenstionHelper.GetActualType <UserType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var user = await _mediator.Send(new GetUserQuery(
                                                        id: context.GetArgument <string>("id"),
                                                        userName: context.GetArgument <string>("userName"),
                                                        email: context.GetArgument <string>("email"),
                                                        loginProvider: context.GetArgument <string>("loginProvider"),
                                                        providerKey: context.GetArgument <string>("providerKey")));

                    await CheckAuthAsync(context.GetCurrentUserId(), user);

                    return(user);
                })
            });

            #region role query

#pragma warning disable S125 // Sections of code should not be commented out

            /*
             *           {
             *            getRole(roleName: "Use api"){
             *             permissions
             *            }
             *          }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Query.AddField(new FieldType
            {
                Name      = "role",
                Arguments = new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                    Name = "roleName"
                }
                    ),
                Type     = GraphTypeExtenstionHelper.GetActualType <RoleType>(),
                Resolver = new AsyncFieldResolver <object>(async context =>
                {
                    var result = await _mediator.Send(new GetRoleQuery(context.GetArgument <string>("roleName")));

                    return(result);
                })
            });

            #region create user

#pragma warning disable S125 // Sections of code should not be commented out

            /*
             * mutation ($command: InputCreateUserType!){
             *  createUser(command: $command){ succeeded errors { code }}
             * }
             * Query variables:
             * {
             *  "command": {
             *  "createdBy": "eXp1", "email": "*****@*****.**", "password":"******", "userName": "******", "userType": "Customer"
             *  }
             * }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Mutation.AddField(FieldBuilder.Create <object, IdentityResult>(typeof(IdentityResultType))
                                         .Name("createUser")
                                         .Argument <NonNullGraphType <InputCreateUserType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <CreateUserCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            #region update user

#pragma warning disable S125 // Sections of code should not be commented out

            /*
             *           mutation ($command: InputUpdateUserType!){
             *            updateUser(command: $command){ succeeded errors { description } }
             *          }
             *          Query variables:
             *          {
             *           "command":{
             *            "isAdministrator": false,
             *            "userType": "Customer",
             *            "roles": [],
             *            "id": "b5d28a83-c296-4212-b89e-046fca3866be",
             *            "userName": "******",
             *            "email": "*****@*****.**"
             *              }
             *          }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Mutation.AddField(FieldBuilder.Create <object, IdentityResult>(typeof(IdentityResultType))
                                         .Name("updateUser")
                                         .Argument <NonNullGraphType <InputUpdateUserType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <UpdateUserCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            #region delete user

#pragma warning disable S125 // Sections of code should not be commented out

            /*
             * mutation ($command: InputDeleteUserType!){
             * deleteUser(command: $command){ succeeded errors { description } }
             * }
             * Query variables:
             * {
             * "command": {
             *  "userNames": ["admin",  "*****@*****.**"]
             * }
             * }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Mutation.AddField(FieldBuilder.Create <object, IdentityResult>(typeof(IdentityResultType))
                                         .Name("deleteUsers")
                                         .Argument <NonNullGraphType <InputDeleteUserType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <DeleteUserCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command, PlatformConstants.Security.Permissions.SecurityDelete);
                return(await _mediator.Send(command));
            })
                                         .FieldType);

            #region update role query

#pragma warning disable S125 // Sections of code should not be commented out

            /*
             *           mutation ($command: InputUpdateRoleType!){
             *            updateRole(command: $command){ succeeded errors { description } }
             *          }
             *          Query variables:
             *          {
             *           "command":{
             *           "id": "graphtest",  "name": "graphtest", "permissions": [
             *              { "name": "order:read", "assignedScopes": [{"scope": "{{userId}}", "type": "OnlyOrderResponsibleScope" }] }
             *            ]
             *           }
             *          }
             */
#pragma warning restore S125 // Sections of code should not be commented out

            #endregion
            _ = schema.Mutation.AddField(FieldBuilder.Create <object, IdentityResult>(typeof(IdentityResultType))
                                         .Name("updateRole")
                                         .Argument <NonNullGraphType <InputUpdateRoleType> >(_commandName)
                                         .ResolveAsync(async context =>
            {
                var command = context.GetArgument <UpdateRoleCommand>(_commandName);
                await CheckAuthAsync(context.GetCurrentUserId(), command, PlatformConstants.Security.Permissions.SecurityUpdate);

                return(await _mediator.Send(command));
            })
                                         .FieldType);
        }