Exemple #1
0
            static object ParseValueList(ListGraphType listGraphType, VariableName variableName, object value)
            {
                if (value == null)
                {
                    return(null);
                }

                // note: a list can have a single child element which will automatically be interpreted as a list of 1 elements. (see below rule)
                // so, to prevent a string as being interpreted as a list of chars (which get converted to strings), we ignore considering a string as an IEnumerable
                if (value is IEnumerable values && !(value is string))
                {
                    // create a list containing the parsed elements in the input list
                    if (values is IList list)
                    {
                        var valueOutputs = new object[list.Count];
                        for (int index = 0; index < list.Count; index++)
                        {
                            // parse/validate values as required by graph type
                            valueOutputs[index] = ParseValue(listGraphType.ResolvedType, new VariableName(variableName, index), list[index]);
                        }
                        return(valueOutputs);
                    }
                    else
                    {
                        var valueOutputs = new List <object>(values is ICollection collection ? collection.Count : 0);
                        int index        = 0;
                        foreach (var val in values)
                        {
                            // parse/validate values as required by graph type
                            valueOutputs.Add(ParseValue(listGraphType.ResolvedType, new VariableName(variableName, index++), val));
                        }
                        return(valueOutputs);
                    }
                }
Exemple #2
0
        public void test_inputs()
        {
            var innerObject = new InputObjectGraphType();

            innerObject.AddField(new FieldType {
                Name = "test", ResolvedType = new StringGraphType(), Type = typeof(StringGraphType)
            });
            var list     = new ListGraphType(innerObject);
            var inputObj = new InputObjectGraphType();

            inputObj.AddField(new FieldType {
                Name = "list", ResolvedType = list, Type = list.GetType()
            });
            var obj   = new ObjectGraphType();
            var field = new FieldType
            {
                Name         = "hello",
                ResolvedType = new StringGraphType(),
                Type         = typeof(StringGraphType),
                Arguments    = new QueryArguments {
                    new QueryArgument(inputObj)
                    {
                        Name = "input"
                    }
                }
            };

            obj.AddField(field);
            var schema = new Schema
            {
                Query = obj
            };

            schema.Initialize();
        }
Exemple #3
0
        public async Task ShouldBeAbleToUseTheSameIndexForMultipleAliases()
        {
            _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.Services.AddSingleton <IIndexPropertyProvider, IndexPropertyProvider <AnimalIndex> >();

                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"
                });

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

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

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

                Assert.Single(cats);
                Assert.Equal("doug", cats.First().As <Animal>().Name);

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

                Assert.Single(dogs);
                Assert.Equal("doug", dogs.First().As <Animal>().Name);
            }
        }
Exemple #4
0
        public async Task ShouldFilterPartsWithoutAPrefixWhenThePartHasNoPrefix()
        {
            _store.RegisterIndexes <AnimalIndexProvider>();

            using (var services = new FakeServiceCollection())
            {
                services.Populate(new ServiceCollection());
                services.Services.AddScoped(x => _store.CreateSession());
                services.Services.AddScoped(x => new ShellSettings());
                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 AnimalPartWhereInput();
                var inputs           = new FieldType {
                    Name = "Inputs", Arguments = new QueryArguments {
                        new QueryArgument <WhereInputObjectGraphType> {
                            Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput
                        }
                    }
                };

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

                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());

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

                Assert.Single(dogs);
                Assert.Equal("doug", dogs.First().As <AnimalPart>().Name);
            }
        }
Exemple #5
0
        public GraphQLQuery(GraphQLService graphQLService, EntityService entityService)
        {
            Name = "Query";
            var schemas = entityService.GetCollectionSchemas();

            foreach (var metaColl in schemas)
            {
                if (Fields.Count(x => x.Name == metaColl.CollectionName) == 0)
                {
                    JObjectRawType type     = new JObjectRawType(this, graphQLService, metaColl, entityService);
                    ListGraphType  listType = new ListGraphType(type);

                    AddField(new FieldType
                    {
                        Name         = metaColl.CollectionName,
                        Type         = listType.GetType(),
                        ResolvedType = listType,
                        Resolver     = new JObjectFieldResolver(graphQLService, entityService),
                        Arguments    = new QueryArguments(
                            type.TableArgs
                            )
                    });
                }
            }
        }
Exemple #6
0
        private void InitGraphField(Field field, Dictionary <string, CollectionSchema> collections = null, GraphQLService graphQLService = null)
        {
            Type graphQLType;

            if (field.BaseType == FieldBaseType.Object)
            {
                var relatedObject     = collections[field.Type];
                var relatedCollection = new CollectionType(relatedObject, collections);
                var listType          = new ListGraphType(relatedCollection);
                graphQLType = relatedCollection.GetType();
                FieldType columnField = Field(
                    graphQLType,
                    relatedObject.CollectionName);

                columnField.Resolver  = new NameFieldResolver();
                columnField.Arguments = new QueryArguments(relatedCollection.TableArgs);
                foreach (var arg in columnField.Arguments.Where(x => !(new string[] { "pageNumber", "pageSize", "rawQuery", "_id" }.Contains(x.Name))).ToList())
                {
                    arg.Name = $"{relatedObject.CollectionName}_{arg.Name}";
                    TableArgs.Add(arg);
                }
            }
            else
            {
                //graphQLType = (ResolveFieldMetaType(field.BaseType)).GetGraphTypeFromType(!field.Required);
                graphQLType = (ResolveFieldMetaType(field.BaseType)).GetGraphTypeFromType(true);
                FieldType columnField = Field(
                    graphQLType,
                    field.Name);

                columnField.Resolver = new NameFieldResolver();
                FillArgs(field.Name, graphQLType);
            }
        }
Exemple #7
0
        public GraphQLQuery(DbDataAdapter data, IDatabaseMetadata dbMetadata)
        {
            _dbMetadata = dbMetadata;
            _dbAdapter  = data;

            Name = "Query";

            foreach (var metaTable in _dbMetadata.GetMetadataTables())
            {
                var tableType = new TableType(metaTable);
                this.AddField(new FieldType()
                {
                    Name         = metaTable.TableName,
                    Type         = tableType.GetType(),
                    ResolvedType = tableType,
                    Resolver     = new MyFieldResolver(metaTable, _dbAdapter),
                    Arguments    = new QueryArguments(
                        tableType.TableArgs
                        )
                });
                //lets add key to get list of current table
                var listType = new ListGraphType(tableType);
                this.AddField(new FieldType {
                    Name         = $"{metaTable.TableName}_list",
                    Type         = listType.GetType(),
                    ResolvedType = listType,
                    Resolver     = new MyFieldResolver(metaTable, _dbAdapter),
                    Arguments    = new QueryArguments(
                        tableType.TableArgs
                        )
                });
            }
        }
Exemple #8
0
        public void IsListType_ListGraphType_ReturnsTrue()
        {
            var graphType = new ListGraphType(new ObjectGraphType());

            var isListType = graphType.IsListType();

            isListType.Should().BeTrue();
        }
Exemple #9
0
        public IGraphType?Visit(IArrayField field, FieldInfo args)
        {
            var schemaFieldType =
                new ListGraphType(
                    new NonNullGraphType(
                        new NestedInputGraphType(builder, args)));

            return(schemaFieldType);
        }
Exemple #10
0
        public ContentCollectionType(ContentCollection contentCollection, Func <IContentStore> getContentStore, string[] languages, string defaultLanguage)
        {
            if (NameConverter.TryConvertToGraphQLName(contentCollection.Name, out string graphQLName))
            {
                Name        = graphQLName;
                Description = "A collection that contains content of a specific type.";

                Field(cc => cc.Id).Description("The id of the content collection.");
                Field(cc => cc.Name).Description("The name of the content collection.");
                Field(cc => cc.Version).Description("The version of the content collection.");
                Field <ContentTypeType>("ContentType");

                var contentItemType = new ContentItemType(contentCollection, languages, defaultLanguage);
                var itemsType       = new ListGraphType(contentItemType);
                this.Field("items",
                           itemsType,
                           arguments: new QueryArguments(
                               new QueryArgument <StringGraphType>()
                {
                    Name = "contentKeyStartsWith"
                },
                               new QueryArgument <IntGraphType>()
                {
                    Name = "first"
                },
                               new QueryArgument <IntGraphType>()
                {
                    Name = "offset"
                }
                               ),
                           resolve: ctx =>
                {
                    var collection = ctx.Source as ContentCollection;
                    if (collection != null)
                    {
                        var contentStore     = getContentStore();
                        var contentItemQuery = new ContentItemQuery
                        {
                            AppId                = contentCollection.ContentType.AppId,
                            CollectionId         = collection.Id,
                            ContentKeyStartsWith = ctx.GetArgument <string>("contentKeyStartsWith"),
                            First                = ctx.GetArgument <int?>("first"),
                            Offset               = ctx.GetArgument <int?>("offset")
                        };
                        return(contentStore.GetContentItems(contentItemQuery));
                    }
                    else
                    {
                        return(null);
                    }
                });
            }
            else
            {
                // TODO: log that a graphQL name could not be generated.
            }
        }
Exemple #11
0
        public IGraphType?Visit(IArrayField field, Args args)
        {
            var schemaFieldType =
                new ListGraphType(
                    new NonNullGraphType(
                        new NestedInputGraphType(args.Model, args.Schema, field, args.SchemaField)));

            return(schemaFieldType);
        }
        private string build_schema(string propType)
        {
            var nestedObjType = new ObjectGraphType
            {
                Name = "NestedObjType"
            };

            nestedObjType.AddField(new FieldType
            {
                ResolvedType = new IntGraphType(),
                Name         = "intField"
            });
            var rootType = new ObjectGraphType {
                Name = "root"
            };
            IGraphType resolvedType;

            switch (propType)
            {
            case "none":
            {
                resolvedType = nestedObjType;
                break;
            }

            case "list":
            {
                resolvedType = new ListGraphType(nestedObjType);
                break;
            }

            case "non-null":
            {
                resolvedType = new NonNullGraphType(nestedObjType);
                break;
            }

            default:
            {
                throw new NotSupportedException();
            }
            }

            rootType.AddField(new FieldType
            {
                Name         = "listOfObjField",
                ResolvedType = resolvedType
            });

            var s = new Schema
            {
                Query = rootType
            };
            var schema = new SchemaPrinter(s).Print();

            return(schema);
        }
 private static bool HasFullSpecifiedResolvedType(IProvideResolvedType type)
 {
     return(type.ResolvedType switch
     {
         null => false,
         ListGraphType list => HasFullSpecifiedResolvedType(list),
         NonNullGraphType nonNull => HasFullSpecifiedResolvedType(nonNull),
         _ => true, // not null
     });
Exemple #14
0
        public IGraphType?Visit(IArrayField field, FieldInfo args)
        {
            if (args.Fields.Count == 0)
            {
                return(null);
            }

            var schemaFieldType =
                new ListGraphType(
                    new NonNullGraphType(
                        new NestedInputGraphType(builder, args)));

            return(schemaFieldType);
        }
        public void AddNavigationProperties(FieldType fieldType)
        {
            Type entityType      = GetEntityTypeFromResolvedType(((ListGraphType)fieldType.ResolvedType).ResolvedType);
            var  entityGraphType = (IObjectGraphType)_clrTypeToObjectGraphType[entityType];

            foreach (PropertyInfo propertyInfo in entityType.GetProperties())
            {
                if (!entityGraphType.HasField(propertyInfo.Name))
                {
                    IGraphType?     resolvedType;
                    QueryArgument[] queryArguments;
                    Type?           itemType = Parsers.OeExpressionHelper.GetCollectionItemTypeOrNull(propertyInfo.PropertyType);
                    if (itemType == null)
                    {
                        if (!_clrTypeToObjectGraphType.TryGetValue(propertyInfo.PropertyType, out resolvedType))
                        {
                            continue;
                        }

                        queryArguments = CreateQueryArguments(propertyInfo.PropertyType, true);
                    }
                    else
                    {
                        if (!_clrTypeToObjectGraphType.TryGetValue(itemType, out resolvedType))
                        {
                            continue;
                        }

                        resolvedType   = new ListGraphType(resolvedType);
                        queryArguments = CreateQueryArguments(itemType, true);
                    }

                    if (IsRequired(propertyInfo))
                    {
                        resolvedType = new NonNullGraphType(resolvedType);
                    }

                    var entityFieldType = new FieldType()
                    {
                        Arguments    = new QueryArguments(queryArguments),
                        Name         = propertyInfo.Name,
                        ResolvedType = resolvedType,
                        Resolver     = new FieldResolver(propertyInfo),
                    };
                    entityGraphType.AddField(entityFieldType);
                }
            }

            fieldType.Arguments = new QueryArguments(CreateQueryArguments(entityType, false));
        }
        /// <summary>
        /// Builds an execution node with the specified parameters.
        /// </summary>
        protected ExecutionNode BuildSubscriptionExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, int?indexInParentNode, object source)
        {
            if (graphType is NonNullGraphType nonNullFieldType)
            {
                graphType = nonNullFieldType.ResolvedType;
            }

            return(graphType switch
            {
                ListGraphType _ => new SubscriptionArrayExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode, source),
                IObjectGraphType _ => new SubscriptionObjectExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode, source),
                IAbstractGraphType _ => new SubscriptionObjectExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode, source),
                ScalarGraphType scalarGraphType => new SubscriptionValueExecutionNode(parent, scalarGraphType, field, fieldDefinition, indexInParentNode, source),
                _ => throw new InvalidOperationException($"Unexpected type: {graphType}")
            });
        public static ExecutionNode BuildExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, int?indexInParentNode = null)
        {
            if (graphType is NonNullGraphType nonNullFieldType)
            {
                graphType = nonNullFieldType.ResolvedType;
            }

            return(graphType switch
            {
                ListGraphType _ => new ArrayExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode),
                IObjectGraphType _ => new ObjectExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode),
                IAbstractGraphType _ => new ObjectExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode),
                ScalarGraphType _ => new ValueExecutionNode(parent, graphType, field, fieldDefinition, indexInParentNode),
                _ => throw new InvalidOperationException($"Unexpected type: {graphType}")
            });
Exemple #18
0
        public ListGraphType AddListObjectType(ObjectGraphType parent, ObjectGraphType listObjectType, Func <IEnumerable <Key>, IEnumerable <Row> > getData)
        {
            var listType = new ListGraphType(listObjectType);

            //parent.Name = "list" + tableModel.Identifier;
            var listMemberName = $"List_{parent.Name}_{listObjectType.Name}";

            parent.FieldAsync(listMemberName, listType,
                              resolve: async ctx =>
            {
                var resultRows = await ResolveRelated(ctx as ReadonlyResolveFieldContext, listMemberName, getData);
                return(resultRows);
            });

            return(listType);
        }
Exemple #19
0
        public IGraphType?Visit(IField <TagsFieldProperties> field, FieldInfo args)
        {
            var type = AllTypes.Strings;

            if (field.Properties?.AllowedValues?.Count > 0 && field.Properties.CreateEnum)
            {
                var @enum = builder.GetEnumeration(args.EnumName, field.Properties.AllowedValues);

                if (@enum != null)
                {
                    type = new ListGraphType(new NonNullGraphType(@enum));
                }
            }

            return(type);
        }
        public ListEntitiesGraphQLType(
            IEntityDescriptor descriptor,
            IIndex <IEntityDescriptor, EntityGraphQLType> entityTypesByDescriptor,
            IIndex <IEntityDescriptor, IRepository> repositoriesByDescriptor)
        {
            Name         = descriptor.Name.Pluralize().Camelize();
            Description  = $"Query all {descriptor.Name.Pluralize().Humanize(LetterCasing.LowerCase)}";
            ResolvedType = new ListGraphType(new NonNullGraphType(entityTypesByDescriptor[descriptor]));

            var repository = repositoriesByDescriptor[descriptor];

            Resolver = new AsyncFieldResolver <IEnumerable <IEntity> >(resolveContext =>
            {
                return(repository.__UNSAFE__ListAsync(resolveContext.CancellationToken));
            });
        }
        public static ExecutionNode BuildExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, string[] path = null)
        {
            path ??= AppendPath(parent.Path, field.Name);

            if (graphType is NonNullGraphType nonNullFieldType)
            {
                graphType = nonNullFieldType.ResolvedType;
            }

            return(graphType switch
            {
                ListGraphType _ => new ArrayExecutionNode(parent, graphType, field, fieldDefinition, path),
                IObjectGraphType _ => new ObjectExecutionNode(parent, graphType, field, fieldDefinition, path),
                IAbstractGraphType _ => new ObjectExecutionNode(parent, graphType, field, fieldDefinition, path),
                ScalarGraphType _ => new ValueExecutionNode(parent, graphType, field, fieldDefinition, path),
                _ => throw new InvalidOperationException($"Unexpected type: {graphType}")
            });
Exemple #22
0
        public void test_outputs()
        {
            var innerObject = new ObjectGraphType();

            innerObject.AddField(new FieldType {
                Name = "test", ResolvedType = new StringGraphType(), Type = typeof(StringGraphType)
            });
            var list = new ListGraphType(innerObject);
            var obj  = new ObjectGraphType();

            obj.AddField(new FieldType {
                Name = "list", ResolvedType = list, Type = list.GetType()
            });
            var schema = new Schema
            {
                Query = obj
            };

            schema.Initialize();
        }
Exemple #23
0
        public GraphQLQuery(
            DbContext dbContext,
            IDatabaseMetadata dbMetadata,
            ITableNameLookup tableNameLookup)
        {
            _dbMetadata      = dbMetadata;
            _tableNameLookup = tableNameLookup;
            _dbContext       = dbContext;

            Name = "Query";

            foreach (var metaTable in _dbMetadata.GetTableMetadatas())
            {
                var tableType         = new TableType(metaTable);
                var friendlyTableName = _tableNameLookup.GetFriendlyName(metaTable.TableName);

                AddField(new FieldType
                {
                    Name         = friendlyTableName,
                    Type         = tableType.GetType(),
                    ResolvedType = tableType,
                    Resolver     = new MyFieldResolver(metaTable, _dbContext),
                    Arguments    = new QueryArguments(
                        tableType.TableArgs
                        )
                });

                // lets add key to get list of current table
                var listType = new ListGraphType(tableType);
                AddField(new FieldType
                {
                    Name         = $"{friendlyTableName}_list",
                    Type         = listType.GetType(),
                    ResolvedType = listType,
                    Resolver     = new MyFieldResolver(metaTable, _dbContext),
                    Arguments    = new QueryArguments(
                        tableType.TableArgs
                        )
                });
            }
        }
Exemple #24
0
        public ContentItemWhereInput(string contentItemName)
        {
            Name = $"{contentItemName}WhereInput";

            Description = $"the {contentItemName} content item filters";

            AddScalarFilterFields <IdGraphType>("contentItemId", "content item id");
            AddScalarFilterFields <IdGraphType>("contentItemVersionId", "the content item version id");
            AddScalarFilterFields <StringGraphType>("displayText", "the display text of the content item");
            AddScalarFilterFields <DateTimeGraphType>("createdUtc", "the date and time of creation");
            AddScalarFilterFields <DateTimeGraphType>("modifiedUtc", "the date and time of modification");
            AddScalarFilterFields <DateTimeGraphType>("publishedUtc", "the date and time of publication");
            AddScalarFilterFields <StringGraphType>("owner", "the owner of the content item");
            AddScalarFilterFields <StringGraphType>("author", "the author of the content item");

            var whereInputType = new ListGraphType(this);

            Field <ListGraphType <ContentItemWhereInput> >("Or", "OR logical operation").ResolvedType   = whereInputType;
            Field <ListGraphType <ContentItemWhereInput> >("And", "AND logical operation").ResolvedType = whereInputType;
            Field <ListGraphType <ContentItemWhereInput> >("Not", "NOT logical operation").ResolvedType = whereInputType;
        }
Exemple #25
0
        public GraphQLQuery(GraphQLService graphQLService)
        {
            Name = "Query";
            foreach (var key in graphQLService.Collections.Keys)
            {
                Library.Schema.CollectionSchema metaColl = graphQLService.Collections[key];
                CollectionType type     = new CollectionType(metaColl, graphQLService.Collections, graphQLService);
                ListGraphType  listType = new ListGraphType(type);

                AddField(new FieldType
                {
                    Name         = metaColl.CollectionName,
                    Type         = listType.GetType(),
                    ResolvedType = listType,
                    Resolver     = new JObjectFieldResolver(graphQLService),
                    Arguments    = new QueryArguments(
                        type.TableArgs
                        )
                });
            }
        }
Exemple #26
0
        public GraphQLQuery(
            DbContext dbContext,
            IDatabaseMetadata dbMetadata,
            ITableNameLookup tableNameLookup)
        {
            _dbMetadata      = dbMetadata;
            _tableNameLookup = tableNameLookup;
            _dbContext       = dbContext;
            Name             = "Query";
            var assem = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.ManifestModule.Name == "Mix.Cms.Lib.dll");

            foreach (var metaTable in _dbMetadata.GetTableMetadatas())
            {
                var type              = assem.GetType(metaTable.AssemblyFullName);
                var tableType         = new TableType(metaTable, type);
                var friendlyTableName = metaTable.TableName;
                // _tableNameLookup.GetFriendlyName(metaTable.TableName);
                AddField(new FieldType
                {
                    Name         = friendlyTableName,
                    Type         = tableType.GetType(),
                    ResolvedType = tableType,
                    Resolver     = new MyFieldResolver(metaTable, _dbContext),
                    Arguments    = new QueryArguments(tableType.TableArgs)
                });
                // lets add key to get list of current table
                var listType = new ListGraphType(tableType);
                AddField(new FieldType
                {
                    Name         = $"{friendlyTableName}_list",
                    Type         = listType.GetType(),
                    ResolvedType = listType,
                    Resolver     = new MyFieldResolver(metaTable, _dbContext),
                    Arguments    = new QueryArguments(
                        tableType.TableArgs
                        )
                });
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name">The name of the connection type</param>
        /// <param name="description">Description of the connection type</param>
        /// <param name="itemType">The used item type</param>
        /// <param name="edgeType">The used edge type</param>
        public DynamicConnectionType(string name, string description, IGraphType itemType, IGraphType edgeType)
        {
            ArgumentValidation.ValidateString(nameof(name), name);
            ArgumentValidation.ValidateString(nameof(description), description);

            Name        = name;
            Description = description;
            Field <IntGraphType>().Name("totalCount")
            .Description(
                "A count of the total number of objects in this connection, ignoring pagination. This allows a client to fetch the first five objects by passing \"5\" as the argument to `first`, then fetch the total count so it could display \"5 of 83\", for example. In cases where we employ infinite scrolling or don't have an exact count of entries, this field will return `null`.");
            Field <NonNullGraphType <PageInfoType> >().Name("pageInfo").Description("Information to aid in pagination.");

            var listType = new ListGraphType(itemType);

            this.Field("items",
                       "A list of all of the objects returned in the connection. This is a convenience field provided for quickly exploring the API; rather than querying for \"{ edges { node } }\" when no edge data is needed, this field can be used instead. Note that when clients like Relay need to fetch the \"cursor\" field on the edge to enable efficient pagination, this shortcut cannot be used, and the full \"{ edges { node } } \" version should be used instead.",
                       listType);

            var edgeListType = new ListGraphType(edgeType);

            this.Field("edges", "Information to aid in pagination.", edgeListType);
        }
        private static IGraphType OnResolvingType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (type == typeof(object))
            {
                return(new JsonScalarGraphType());
            }

            if (type == typeof(string))
            {
                return(new StringGraphType());
            }

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>))
            {
                var inner = type.GetGenericArguments()[0];
                var list  = new ListGraphType(OnResolvingType(inner));
                return(list);
            }

            if (type.IsArray && type.GetElementType() != null)
            {
                var inner = type.GetElementType();
                var list  = new ListGraphType(OnResolvingType(inner));
                return(list);
            }

            var graphType = typeof(GoodObjectGraphType <>).MakeGenericType(new[] { type });
            var complex   = (IComplexGraphType)Activator.CreateInstance(graphType, new[] { type });

            complex.Name = type.Name;

            return(complex);
        }
        private IGraphTypeOfGraphQLNet Convert(IGraphType graphType, bool input, ISchema root)
        {
            try
            {
                //Union
                if (graphType.OtherTypes.Any() && !input)
                {
                    var list = new List <IObjectGraphType>();
                    var convertedGraphType = (IObjectGraphType)Convert(_graphTypeProvider.GetGraphType(graphType.Type, false, false), false, root);
                    convertedGraphType.IsTypeOf = _ => true;
                    root.RegisterType(convertedGraphType);
                    list.Add(convertedGraphType);
                    foreach (var type in graphType.OtherTypes)
                    {
                        convertedGraphType          = (IObjectGraphType)Convert(_graphTypeProvider.GetGraphType(type, false, false), false, root);
                        convertedGraphType.IsTypeOf = _ => true;
                        root.RegisterType(convertedGraphType);
                        list.Add(convertedGraphType);
                    }
                    var unionType = new UnionGraphType {
                        PossibleTypes = list
                    };
                    root.RegisterType(unionType);
                    return(unionType);
                }

                //Enumerable
                if (graphType.IsEnumerable)
                {
                    var elementGraphType = _graphTypeProvider.GetGraphType(graphType.Type, false, false);
                    var listGraphType    = new ListGraphType(Convert(elementGraphType, input, root));
                    return(graphType.IsRequired
                        ? new NonNullGraphType(listGraphType)
                        : (IGraphTypeOfGraphQLNet)listGraphType);
                }

                //Scalar
                if (!graphType.Fields.Any())
                {
                    if (graphType.IsEnum)
                    {
                        var enumGraphType = typeof(EnumerationGraphType <>).MakeGenericType(graphType.Type);
                        enumGraphType = graphType.IsRequired
                            ? typeof(NonNullGraphType <>).MakeGenericType(enumGraphType)
                            : enumGraphType;
                        return((IGraphTypeOfGraphQLNet)Activator.CreateInstance(enumGraphType));
                    }

                    if (graphType.Type == typeof(string))
                    {
                        var stringType = new StringGraphType();
                        return(graphType.IsRequired
                            ? (IGraphTypeOfGraphQLNet) new NonNullGraphType(stringType)
                            : stringType);
                    }
                    var scalarType = graphType.Type.IsGenericType && graphType.Type.GetGenericTypeDefinition() == typeof(Nullable <>)
                       ? GraphTypeTypeRegistry.Get(graphType.Type.GenericTypeArguments[0])
                       : GraphTypeTypeRegistry.Get(graphType.Type);

                    if (null != scalarType)
                    {
                        var resolvedGraphType = (IGraphTypeOfGraphQLNet)Activator.CreateInstance(scalarType);
                        return(graphType.IsRequired
                            ? new NonNullGraphType(resolvedGraphType)
                            : resolvedGraphType);
                    }

                    throw new GraphException($"Unknown GraphType '{graphType.Name}'");
                }

                //Complex
                var objectGraphType = input
                    ? (IComplexGraphType) new InputObjectGraphType {
                    Name = $"{graphType.Name}Input"
                }
                    : new ObjectGraphType {
                    Name = graphType.Name
                };
                foreach (var field in graphType.Fields.Values)
                {
                    var fieldType = new FieldType
                    {
                        Name         = field.Name,
                        ResolvedType = Convert(field.GraphType, input, root)
                    };
                    if (field.Arguments.Any())
                    {
                        fieldType.Arguments = new QueryArguments();
                    }
                    foreach (var argument in field.Arguments.Values)
                    {
                        var queryArgument = new QueryArgument(Convert(argument.GraphType, input, root))
                        {
                            Name = argument.Name
                        };
                        fieldType.Arguments.Add(queryArgument);
                    }
                    objectGraphType.AddField(fieldType);
                }

                return(graphType.IsRequired
                    ? (IGraphTypeOfGraphQLNet) new NonNullGraphType(objectGraphType)
                    : objectGraphType);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #30
0
        public async Task ShouldFilterOnMultipleIndexesOnSameAlias()
        {
            _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());

                context.Arguments["where"] = JObject.Parse("{ animals: { name: \"doug\", isScary: true } }");
                var animals = await((AsyncFieldResolver <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);
            }
        }