Beispiel #1
0
 object IFieldResolver.Resolve(ResolveFieldContext context)
 {
     return Resolve(context);
 }
Beispiel #2
0
 public IEnumerable <Author> GetAuthors(ResolveFieldContext context)
 {
     return(authorsDataSource.GetAuthors()
            .Select(a => ConvertToGraphQLAuthor(a, ShouldIncludeBooks(context))));
 }
Beispiel #3
0
        public async Task <HistoricalMeasurementBySite> RequestLatestMinuteHistoryBySite(ResolveFieldContext context, int siteid, int beforemin)
        {
            if (context.ThrowIfInvalidAuthorization() == false)
            {
                return(null);
            }

            var sites = context.GetAllSiteIds();

            if (sites.Contains(siteid) == false)
            {
                context.Errors.Add(new GraphQL.ExecutionError("대상 사이트는 소유하지 않았습니다"));
                return(null);
            }
            HistoricalMeasurementBySite summary = new HistoricalMeasurementBySite();
            double sumOfChg = await influxDataAccess.Query("sum_chg_1m", "sumOfChg", site, start, end);
        }
        public object Resolve(ResolveFieldContext context)
        {
            var parameter = context.GetArgument <GetMessagesParameterModel>("parameter");

            return(_getMessages.Execute(parameter).ToTask());
        }
Beispiel #5
0
 public IEnumerable <Book> GetBooks(ResolveFieldContext context)
 {
     return(booksDataSource.GetBooks()
            .Select(b => ConvertToGraphQLBook(b, ShouldIncludeAuthor(context))));
 }
Beispiel #6
0
 protected virtual async Task <TResult> InternalResolve(ResolveFieldContext <object> context)
 {
     //you can add your custom logic here before the original Resolve method.
     return(await Resolve(context));
 }
        public async Task ShouldFilterOnMultipleIndexesOnSameAlias()
        {
            await _initializeTask;

            _store.RegisterIndexes <AnimalIndexProvider>();
            _store.RegisterIndexes <AnimalTraitsIndexProvider>();

            using (var services = new FakeServiceCollection())
            {
                services.Populate(new ServiceCollection());
                services.Services.AddScoped(x => new ShellSettings());
                services.Services.AddScoped(x => _store.CreateSession());
                services.Services.AddScoped <IIndexProvider, ContentItemIndexProvider>();
                services.Services.AddScoped <IIndexProvider, AnimalIndexProvider>();
                services.Services.AddScoped <IIndexProvider, AnimalTraitsIndexProvider>();
                services.Services.AddScoped <IIndexAliasProvider, MultipleIndexesIndexProvider>();
                services.Build();

                var retrunType = new ListGraphType <StringGraphType>();
                retrunType.ResolvedType = new StringGraphType()
                {
                    Name = "Animal"
                };

                var context = new ResolveFieldContext
                {
                    Arguments   = new Dictionary <string, object>(),
                    UserContext = new GraphQLContext
                    {
                        ServiceProvider = services
                    },
                    ReturnType = retrunType
                };

                var ci = new ContentItem {
                    ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1"
                };
                ci.Weld(new Animal {
                    Name = "doug", IsHappy = true, IsScary = false
                });

                var ci1 = new ContentItem {
                    ContentType = "Animal", Published = true, ContentItemId = "2", ContentItemVersionId = "2"
                };
                ci1.Weld(new Animal {
                    Name = "doug", IsHappy = false, IsScary = true
                });

                var ci2 = new ContentItem {
                    ContentType = "Animal", Published = true, ContentItemId = "3", ContentItemVersionId = "3"
                };
                ci2.Weld(new Animal {
                    Name = "tommy", IsHappy = false, IsScary = true
                });


                var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService <ISession>();
                session.Save(ci);
                session.Save(ci1);
                session.Save(ci2);
                await session.CommitAsync();

                var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings {
                    DefaultNumberOfResults = 10
                }));

                context.Arguments["where"] = JObject.Parse("{ animals: { name: \"doug\", isScary: true } }");
                var animals = await((LockedAsyncFieldResolver <IEnumerable <ContentItem> >)type.Resolver).Resolve(context);

                Assert.Single(animals);
                Assert.Equal("doug", animals.First().As <Animal>().Name);
                Assert.True(animals.First().As <Animal>().IsScary);
                Assert.False(animals.First().As <Animal>().IsHappy);
            }
        }
 public bool Four(ResolveFieldContext resolveContext, object source, MyUserContext context, int id)
 {
     return(resolveContext != null && context != null && source != null && id != 0);
 }
        public Task <string> GetTwoAsync(ResolveFieldContext context)
        {
            context.CancellationToken.ThrowIfCancellationRequested();

            return(Task.FromResult("two"));
        }
 public string ResolveWithParam(ResolveFieldContext context, string id)
 {
     return($"Resolved {id}");
 }
 public bool Three(ResolveFieldContext resolveContext, object source, MyUserContext context)
 {
     return(resolveContext != null && context != null && source != null);
 }
 public string Resolve(ResolveFieldContext context)
 {
     return("Resolved");
 }
Beispiel #13
0
 public Message ResolveMessageAddedByUserAsync(ResolveFieldContext context)
 {
     return(context.Source as Message);
 }
Beispiel #14
0
        private OrderEvent ResolveEvent(ResolveFieldContext context)
        {
            var orderEvent = context.Source as OrderEvent;

            return(orderEvent);
        }
Beispiel #15
0
        public async Task <Room> RemoveRoom(ResolveFieldContext <object> context)
        {
            var id = context.GetArgument <int>("id");

            return(await _unitOfWork.RoomRepository.Remove(id));
        }
Beispiel #16
0
 public static IQueryable <TItem> ApplyGraphQlArguments <TItem, TSource>(this IQueryable <TItem> queryable, ResolveFieldContext <TSource> context, List <string> keyNames = null)
     where TItem : class
 {
     Guard.AgainstNull(nameof(queryable), queryable);
     Guard.AgainstNull(nameof(context), context);
     return(ApplyToAll(queryable, (type, x) => context.GetArgument(type, x), keyNames));
 }
Beispiel #17
0
 private ChatModels.Message ResolveMessage(ResolveFieldContext context)
 {
     return(context.Source as ChatModels.Message);
 }
 private object ResolveCount(ResolveFieldContext <IGraphQlQueryOptions> context)
 {
     return(context.Source.Count());
 }
Beispiel #19
0
 protected abstract Task <TResult> Resolve(ResolveFieldContext <object> context);
Beispiel #20
0
        public static IQueryable <Produto> Resolve <TSourceContext>(ResolveFieldContext <TSourceContext> context)
        {
            var query     = StaticDataBase.GetQueryProdutos();
            int?produtoId = context.GetArgument <int?>("id");

            if (produtoId.HasValue)
            {
                if (produtoId.Value <= 0)
                {
                    context.Errors.Add(new ExecutionError("Id não deve ser menor ou igual a zero!"));
                    return(null);
                }
                return(query.Where(w => w.Id == produtoId));
            }

            string descricao = context.GetArgument <string>("descricao");

            if (!string.IsNullOrEmpty(descricao))
            {
                return(query.Where(w => w.Descricao == descricao));
            }

            string codigoBarras = context.GetArgument <string>("codigoBarras");

            if (!string.IsNullOrEmpty(codigoBarras))
            {
                return(query.Where(w => w.CodigoBarras == codigoBarras));
            }

            bool?controlaValidade = context.GetArgument <bool?>("controlaValidade");

            if (controlaValidade.HasValue)
            {
                return(query.Where(w => w.ControlaValidade == controlaValidade));
            }

            DateTime?validadeGt = context.GetArgument <DateTime?>("validade_gt");

            if (validadeGt.HasValue)
            {
                return(query.Where(w => w.DataValidade >= validadeGt));
            }

            DateTime?validadeLt = context.GetArgument <DateTime?>("validade_lt");

            if (validadeLt.HasValue)
            {
                return(query.Where(w => w.DataValidade <= validadeLt));
            }

            DateTime?validadeEq = context.GetArgument <DateTime?>("validade_eq");

            if (validadeEq.HasValue)
            {
                return(query.Where(w => w.DataValidade == validadeLt));
            }

            int?estoqueGt = context.GetArgument <int?>("estoque_gt");

            if (estoqueGt.HasValue)
            {
                return(query.Where(w => w.Estoque >= estoqueGt));
            }

            int?estoqueLt = context.GetArgument <int?>("estoque_lt");

            if (estoqueLt.HasValue)
            {
                return(query.Where(w => w.Estoque <= estoqueLt));
            }

            int?estoqueEq = context.GetArgument <int?>("estoque_eq");

            if (estoqueEq.HasValue)
            {
                return(query.Where(w => w.Estoque == estoqueEq));
            }

            return(query);
        }
        public async Task ShouldFilterByCollapsedWhereInputForCollapsedParts()
        {
            await _initializeTask;

            _store.RegisterIndexes <AnimalIndexProvider>();

            using (var services = new FakeServiceCollection())
            {
                services.Populate(new ServiceCollection());
                services.Services.AddScoped(x => new ShellSettings());
                services.Services.AddScoped(x => _store.CreateSession());
                services.Services.AddScoped <IIndexProvider, ContentItemIndexProvider>();
                services.Services.AddScoped <IIndexProvider, AnimalIndexProvider>();
                services.Services.AddScoped <IIndexAliasProvider, MultipleAliasIndexProvider>();
                services.Build();

                var returnType = new ListGraphType <StringGraphType>();
                returnType.ResolvedType = new StringGraphType()
                {
                    Name = "Animal"
                };

                var animalWhereInput = new AnimalPartCollapsedWhereInput();

                var context = new ResolveFieldContext
                {
                    Arguments   = new Dictionary <string, object>(),
                    UserContext = new GraphQLContext
                    {
                        ServiceProvider = services
                    },
                    ReturnType      = returnType,
                    FieldDefinition = new FieldType
                    {
                        Name      = "Inputs",
                        Arguments = new QueryArguments
                        {
                            new QueryArgument <WhereInputObjectGraphType>
                            {
                                Name         = "where",
                                Description  = "filters the animals",
                                ResolvedType = animalWhereInput
                            }
                        }
                    }
                };

                var ci = new ContentItem {
                    ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1"
                };
                ci.Weld(new AnimalPart {
                    Name = "doug"
                });

                var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService <ISession>();
                session.Save(ci);
                await session.CommitAsync();

                var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings {
                    DefaultNumberOfResults = 10
                }));

                context.Arguments["where"] = JObject.Parse("{ name: \"doug\" }");
                var dogs = await((LockedAsyncFieldResolver <IEnumerable <ContentItem> >)type.Resolver).Resolve(context);

                Assert.Single(dogs);
                Assert.Equal("doug", dogs.First().As <AnimalPart>().Name);
            }
        }
Beispiel #22
0
 public object Resolve(ResolveFieldContext context)
 {
     return(ResolveAsync(context));
 }
Beispiel #23
0
 private bool ShouldIncludeBooks(ResolveFieldContext context) => context.SubFields?.ContainsKey("books") ?? false;
Beispiel #24
0
 public static Swapi Api <TSource>(this ResolveFieldContext <TSource> context)
 {
     return(((GraphQLContext)context.UserContext).Api);
 }
Beispiel #25
0
 private bool ShouldIncludeAuthor(ResolveFieldContext context) => context.SubFields?.ContainsKey("author") ?? false;
 public static IEnumerable <TItem> ApplyGraphQlArguments <TItem, TSource>(this IEnumerable <TItem> items, ResolveFieldContext <TSource> context)
 {
     Guard.AgainstNull(nameof(items), items);
     Guard.AgainstNull(nameof(context), context);
     return(ApplyToAll(items, (type, x) => context.GetArgument(type, x)));
 }
        private MessageFrom ResolveFrom(ResolveFieldContext <Message> context)
        {
            var message = context.Source;

            return(message.From);
        }
Beispiel #28
0
        public async Task <Room> AddRoom(ResolveFieldContext <object> context)
        {
            var room = context.GetArgument <Room>("room");

            return(await _unitOfWork.RoomRepository.Add(room));
        }
Beispiel #29
0
 public abstract TOut MutateAndGetPayload(MutationInputs inputs, ResolveFieldContext <object> context);
        private static async Task <object> ToHtml(ResolveFieldContext <MarkdownField> ctx)
        {
            if (string.IsNullOrEmpty(ctx.Source.Markdown))
            {
                return(ctx.Source.Markdown);
            }

            var serviceProvider  = ctx.ResolveServiceProvider();
            var markdownService  = serviceProvider.GetRequiredService <IMarkdownService>();
            var shortcodeService = serviceProvider.GetRequiredService <IShortcodeService>();

            var contentDefinitionManager = serviceProvider.GetRequiredService <IContentDefinitionManager>();

            var jObject = ctx.Source.Content as JObject;
            // The JObject.Path is consistent here even when contained in a bag part.
            var jsonPath                  = jObject.Path;
            var paths                     = jsonPath.Split('.');
            var partName                  = paths[0];
            var fieldName                 = paths[1];
            var contentTypeDefinition     = contentDefinitionManager.GetTypeDefinition(ctx.Source.ContentItem.ContentType);
            var contentPartDefinition     = contentTypeDefinition.Parts.FirstOrDefault(x => string.Equals(x.Name, partName));
            var contentPartFieldDefintion = contentPartDefinition.PartDefinition.Fields.FirstOrDefault(x => string.Equals(x.Name, fieldName));

            var settings = contentPartFieldDefintion.GetSettings <MarkdownFieldSettings>();

            // The default Markdown option is to entity escape html
            // so filters must be run after the markdown has been processed.
            var html = markdownService.ToHtml(ctx.Source.Markdown);

            // The liquid rendering is for backwards compatability and can be removed in a future version.
            if (!settings.SanitizeHtml)
            {
                var liquidTemplateManager = serviceProvider.GetService <ILiquidTemplateManager>();
                var htmlEncoder           = serviceProvider.GetService <HtmlEncoder>();

                var model = new MarkdownFieldViewModel()
                {
                    Markdown            = ctx.Source.Markdown,
                    Html                = html,
                    Field               = ctx.Source,
                    Part                = ctx.Source.ContentItem.Get <ContentPart>(partName),
                    PartFieldDefinition = contentPartFieldDefintion
                };

                html = await liquidTemplateManager.RenderAsync(html, htmlEncoder, model,
                                                               scope => scope.SetValue("ContentItem", ctx.Source.ContentItem));
            }

            html = await shortcodeService.ProcessAsync(html,
                                                       new Context
            {
                ["ContentItem"]         = ctx.Source.ContentItem,
                ["PartFieldDefinition"] = contentPartFieldDefintion
            });

            if (settings.SanitizeHtml)
            {
                var htmlSanitizerService = serviceProvider.GetRequiredService <IHtmlSanitizerService>();
                html = htmlSanitizerService.Sanitize(html);
            }

            return(html);
        }