Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Mediatr
            services.AddMediatR(typeof(Startup));

            // Add GraphQL services and configure options
            services
            .AddSingleton <TopLevelResolver>()
            .AddSingleton <AnyScalarGraphType>()
            .AddSingleton <ServiceGraphType>()
            .AddSingleton(provider =>
            {
                return(FederatedSchema.For(File.ReadAllText("schema.gql"), schemaBuilder =>
                {
                    schemaBuilder.ServiceProvider = provider;
                    schemaBuilder.Types.Include <TopLevelResolver>();
                }));
            })
            .AddGraphQL((options, provider) =>
            {
                var env = provider.GetRequiredService <IWebHostEnvironment>();
                options.EnableMetrics = env.IsDevelopment();
                var logger            = provider.GetRequiredService <ILogger <Startup> >();
                options.UnhandledExceptionDelegate = ctx => logger.LogError("{Error} occured", ctx.OriginalException.Message);
            })
            .AddSystemTextJson(deserializerSettings => { }, serializerSettings => { })
            .AddErrorInfoProvider((opt, provider) =>
            {
                var env = provider.GetRequiredService <IWebHostEnvironment>();
                opt.ExposeExceptionStackTrace = env.IsDevelopment();
            })
            .AddDataLoader();
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            var schemaPath = "schema.graphql";
            var schema     = File.ReadAllText(schemaPath);

            var federatedSchema = FederatedSchema.For(schema, _ => { });
            var printer         = new FederatedSchemaPrinter(federatedSchema);

            Console.WriteLine(printer.PrintFederatedSchema());
        }
Esempio n. 3
0
    public void PrintObject_ReturnsEmptyString_GivenQueryTypeHasOnlyFederatedFields(string definitions, string expected)
    {
        // Arrange
        var schema = FederatedSchema.For(definitions);
        SchemaPrinterOptions options = default;

        schema.Initialize();

        var query = schema.Query;
        var federatedSchemaPrinter = new FederatedSchemaPrinter(schema, options);

        // Act
        string result = federatedSchemaPrinter.PrintObject(query);

        // Assert
        Assert.Equal(expected, result);
    }
Esempio n. 4
0
        public void PrintObject_ReturnsEmptyString_GivenQueryTypeHasOnlyFederatedFields()
        {
            // Arrange
            var schema = FederatedSchema.For(@"type X @key(fields: ""id"") { id: ID! }");
            SchemaPrinterOptions options = default;

            schema.Initialize();

            var query = schema.Query;
            var federatedSchemaPrinter = new FederatedSchemaPrinter(schema, options);

            // Act
            string result = federatedSchemaPrinter.PrintObject(query);

            // Assert
            Assert.Equal(string.Empty, result);
        }
Esempio n. 5
0
        /// <summary>
        /// Builds the federated schema
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        private static ISchema BuildSchema(IServiceProvider serviceProvider)
        {
            return(FederatedSchema.For(string.Join("", new List <string> {
                IdentitySchema.Definition
            }), _ =>
            {
                _.ServiceProvider = serviceProvider;

                _.Types.Include <Query>();
                _.Types.Include <IdentityType>();
                _.Types.Include <UserType>();

                _.Types.Include <Mutation>();
                _.Types.Include <IdentityOpsType>();
                _.Types.Include <RegisterInputType>();
                _.Types.Include <LoginInputType>();
            }));
        }
Esempio n. 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // GraphQL types
            services.AddSingleton <IDocumentWriter, DocumentWriter>();
            services.AddSingleton <IDocumentExecuter, DocumentExecuter>();

            // Apollo Federation Types
            services.AddSingleton <AnyScalarGraphType>();
            services.AddSingleton <ServiceGraphType>();

            // Custom Types
            services.AddSingleton <UsersStore>();
            services.AddTransient <Query>();

            services.AddTransient <ISchema>(s =>
            {
                var store = s.GetRequiredService <UsersStore>();

                return(FederatedSchema.For(@"
                    extend type Query {
                        me: User
                    }

                    type User @key(fields: ""id"") {
                        id: ID!
                        name: String
                        username: String
                    }
                ", _ =>
                {
                    _.ServiceProvider = s;
                    _.Types.Include <Query>();
                    _.Types.For("User").ResolveReferenceAsync(context =>
                    {
                        var id = (string)context.Arguments["id"];
                        return store.GetUserById(id);
                    });
                }));
            });
        }
        public static ISchema BuildFederatedSchema(IServiceProvider serviceProvider)
        {
            var schema = File.ReadAllText(_schemaPath);

            return(FederatedSchema.For(schema, _ =>
            {
                _.ServiceProvider = serviceProvider;
                _.Types
                .Include <Author>();
                _.Types
                .Include <BookType>();
                _.Types
                .Include <AuthorInput>();
                _.Types
                .Include <AuthorQuery>();
                _.Types
                .Include <AuthorMutation>();
                _.Types
                .For(nameof(Author))
                .ResolveReferenceAsync(async context =>
                {
                    using var scope = serviceProvider.CreateScope();
                    //var logger = scope.ServiceProvider.GetRequiredService<ILogger>();
                    var authorRepository = scope.ServiceProvider.GetRequiredService <IAuthorRepository>();

                    //logger.LogDebug("Parsing id for aggregate root");

                    var id = Guid.Parse((string)context.Arguments["id"]);

                    //logger.LogDebug("Resolving reference for {AggregateRootName} by id {Id}", nameof(Author), id);
                    var author = await authorRepository.RetrieveAuthorByAuthorIdAsync(id);

                    var result = author.AsAuthorType();

                    return result;
                });
            }));
        }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddControllerServices()
            .AddDbServices(Configuration)
            .AddMediatRServices()
            .AddSingleton <AnyScalarGraphType>()
            .AddSingleton <ServiceGraphType>()
            .AddSingleton <Schema.Book>()
            .AddSingleton <Schema.Author>()
            .AddSingleton <BookInput>()
            .AddSingleton <BookQuery>()
            .AddSingleton <BookMutation>()
            .AddSingleton <ISchema>(s =>
            {
                var schema = File.ReadAllText(_schemaPath);

                return(FederatedSchema.For(schema, _ =>
                {
                    _.ServiceProvider = s;
                    _.Types
                    .Include <Schema.Book>();
                    _.Types
                    .Include <Schema.Author>();
                    _.Types
                    .Include <BookInput>();
                    _.Types
                    .Include <BookQuery>();
                    _.Types
                    .Include <BookMutation>();
                    _.Types
                    .For("Book")
                    .ResolveReferenceAsync(async context =>
                    {
                        using var scope = s.CreateScope();
                        var logger = scope.ServiceProvider.GetRequiredService <ILogger <Startup> >();
                        var bookRepository = scope.ServiceProvider.GetRequiredService <IBookRepository>();
                        try
                        {
                            logger.LogDebug("Parsing id for aggregate root");

                            var id = Guid.Parse((string)context.Arguments["id"]);

                            logger.LogDebug("Resolving reference for {AggregateRootName} by id {Id}", nameof(Domain.BookAggregate.Book), id);
                            var book = await bookRepository.RetrieveBookByBookIdAsync(id);

                            logger.LogDebug("({@AggregateRoot})", book);
                            logger.LogDebug("Book: Id {Id}, Title {Title}, Overview {Overview}, AuthorId {AuthorId}, Isbn {ISBN}, Publiser {Publisher}, PublicationDate {PublicationDate}, Pages {Pages}", book.Id, book.Title, book.Overview, book.Author.Id, book.Isbn, book.Publisher, book.PublicationDate, book.Pages);
                            logger.LogDebug("Extending {AggregateRoot} as {GraphType}", nameof(Domain.BookAggregate.Book), nameof(Domain.BookAggregate.Book));
                            var result = book.AsBookType();

                            logger.LogDebug("BookType: Id {Id}, Title {Title}, Overview {Overview}, AuthorId {AuthorId}, Isbn {ISBN}, Publiser {Publisher}, PublicationDate {PublicationDate}, Pages {Pages}", result.Id, result.Title, result.Overview, result.Author.Id, result.Isbn, result.Publisher, result.PublicationDate, result.Pages);

                            logger.LogDebug("Returning result ({@Result})", book);
                            //var taskResult = Task.FromResult(result);
                            return book;
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "Something messed up?");
                            throw;
                        }
                    });
                }));
            })
            .AddGraphQL(options =>
            {
                options.EnableMetrics = true;
            })
            .AddSystemTextJson();
        }
Esempio n. 9
0
        public static IServiceCollection AddGraphQLServices(this IServiceCollection services)
        {
            services
            .AddSingleton <AnyScalarGraphType>()
            .AddSingleton <ServiceGraphType>()
            .AddSingleton <Schema.Book>()
            .AddSingleton <Schema.Author>()
            .AddSingleton <BookInput>()
            .AddSingleton <BookQuery>()
            .AddSingleton <BookMutation>()
            .AddTransient <ISchema>(s =>
            {
                //var books = s.GetRequiredService<IBookService>();

                return(FederatedSchema.For(@"
                        type Book @key(fields: ""id"") {
                            id: ID!
                            title: String
                            overview: String
                            author: Author
                            isbn: Long
                            publisher: String
                            publicationDate: Date
                            pages: Int
                        }

                        extend type Author @key(fields: ""id"") {
                                    id: ID! @external
                        }

                        input BookInput {
                            title: String!
                            overview: String!
                            authorId: String!
                            isbn: Long!
                            publisher: String!
                            publicationDate: Date!
                            pages: Int!
                        }

                        extend type Query {
                            books:[Book!]
                            book(id: ID!): Book
                        }

                        extend type Mutation {
                            createBook(bookInput: BookInput): Book
                        }
                    ", _ =>
                {
                    _.ServiceProvider = s;
                    _.Types
                    .Include <Schema.Book>();
                    _.Types
                    .Include <Schema.Author>();
                    _.Types
                    .Include <BookInput>();
                    _.Types
                    .Include <BookQuery>();
                    _.Types
                    .Include <BookMutation>();
                    _.Types
                    .For("Book")
                    .ResolveReferenceAsync(async context =>
                    {
                        using var scope = s.CreateScope();
                        var logger = scope.ServiceProvider.GetRequiredService <ILogger>();
                        var bookRepository = scope.ServiceProvider.GetRequiredService <IBookRepository>();

                        logger.LogDebug("Parsing id for aggregate root");

                        var id = Guid.Parse((string)context.Arguments["id"]);

                        logger.LogDebug("Resolving reference for {AggregateRootName} by id {Id}", nameof(Domain.BookAggregate.Book), id);
                        var book = await bookRepository.RetrieveBookByBookIdAsync(id);

                        var result = book.AsBookType();

                        return result;
                    });
                }));
            })
            .AddGraphQL()
            .AddSystemTextJson();

            return(services);
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMediatR(typeof(Startup));

            // Add GraphQL services and configure options
            services
            .AddSingleton <TopLevelResolver>()
            .AddSingleton <MovieResolver>()
            .AddSingleton <ReviewResolver>()
            .AddSingleton <AnyScalarGraphType>()
            .AddSingleton <ServiceGraphType>()
            .AddSingleton(provider =>
            {
                return(FederatedSchema.For(File.ReadAllText("schema.gql"), schemaBuilder =>
                {
                    schemaBuilder.ServiceProvider = provider;
                    schemaBuilder.Types.Include <TopLevelResolver>();
                    schemaBuilder.Types.Include <MovieResolver>();
                    schemaBuilder.Types.Include <ReviewResolver>();
                    // reference resolvers
                    schemaBuilder.Types.For("Review").ResolveReferenceAsync(ctx =>
                    {
                        var mediator = provider.GetRequiredService <IMediator>();
                        var reviewId = (string)ctx.Arguments["id"];
                        return mediator.Send(new GetReviewById.Request(reviewId));
                    });
                }));
            })
            .AddGraphQL((options, provider) =>
            {
                var env = provider.GetRequiredService <IWebHostEnvironment>();
                options.EnableMetrics = env.IsDevelopment();
                var logger            = provider.GetRequiredService <ILogger <Startup> >();
                options.UnhandledExceptionDelegate = ctx => logger.LogError("{Error} occured", ctx.OriginalException.Message);
            })
            .AddSystemTextJson(deserializerSettings => { }, serializerSettings => { })
            .AddErrorInfoProvider((opt, provider) =>
            {
                var env = provider.GetRequiredService <IWebHostEnvironment>();
                opt.ExposeExceptionStackTrace = env.IsDevelopment();
            })
            .AddDataLoader();

            services.AddSingleton <GetReviewsContext>(serviceProvider => () => new[]
            {
                new Review {
                    Id = "1111", MovieId = "111", Stars = 4.7, Message = "Outstanding movie with a haunting performance and best character development ever seen.", ContainsSpoilers = false, Created = new DateTime(2019, 09, 10)
                },
                new Review {
                    Id = "1112", MovieId = "111", Stars = 4.4, Message = "A psychological study, rather than a superhero flick.", ContainsSpoilers = true, Created = new DateTime(2019, 10, 03)
                },
                new Review {
                    Id = "1113", MovieId = "111", Stars = 3.9, Message = "Joaquin 'OSCAR', Joker = best Dark suspense thriller ... Darker than dark Knight.", ContainsSpoilers = false, Created = new DateTime(2019, 09, 10)
                },
                new Review {
                    Id = "2221", MovieId = "222", Stars = 4.7, Message = "For the first time in forever a true Disney classic is realized.", ContainsSpoilers = true, Created = new DateTime(2019, 10, 07)
                },
                new Review {
                    Id = "2222", MovieId = "222", Stars = 4.2, Message = "A funny and unpredictable Disney Princess musical.", ContainsSpoilers = false, Created = new DateTime(2019, 09, 01)
                },
                new Review {
                    Id = "3331", MovieId = "333", Stars = 4.8, Message = "Downright not awful!", ContainsSpoilers = false, Created = new DateTime(2019, 10, 04)
                }
            });
        }