Search in sources :

Example 1 with GraphQLContext

use of graphql.GraphQLContext in project spring-graphql by spring-projects.

the class DefaultBatchLoaderRegistryTests method mappedBatchLoader.

@Test
void mappedBatchLoader() throws Exception {
    AtomicReference<String> valueRef = new AtomicReference<>();
    this.batchLoaderRegistry.forTypePair(Long.class, Book.class).withOptions(// DataLoader invoked immediately
    options -> options.setBatchingEnabled(false)).registerMappedBatchLoader((ids, environment) -> Mono.deferContextual(contextView -> {
        valueRef.set(contextView.get("key"));
        return Flux.fromIterable(ids).map(BookSource::getBook).collectMap(Book::getId, Function.identity());
    }));
    GraphQLContext graphQLContext = initGraphQLContext(Context.of("key", "value"));
    this.batchLoaderRegistry.registerDataLoaders(this.dataLoaderRegistry, graphQLContext);
    Map<String, DataLoader<?, ?>> map = this.dataLoaderRegistry.getDataLoadersMap();
    assertThat(map).hasSize(1).containsKey(Book.class.getName());
    // Invoke DataLoader to check the context
    ((DataLoader<Long, Book>) map.get(Book.class.getName())).load(1L).get();
    assertThat(valueRef.get()).isEqualTo("value");
}
Also used : DataLoaderRegistry(org.dataloader.DataLoaderRegistry) ContextView(reactor.util.context.ContextView) StatisticsCollector(org.dataloader.stats.StatisticsCollector) Context(reactor.util.context.Context) BookSource(org.springframework.graphql.BookSource) NoOpStatisticsCollector(org.dataloader.stats.NoOpStatisticsCollector) Mono(reactor.core.publisher.Mono) DataLoader(org.dataloader.DataLoader) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Book(org.springframework.graphql.Book) ExecutionInput(graphql.ExecutionInput) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) GraphQLContext(graphql.GraphQLContext) Map(java.util.Map) AssertionsForInterfaceTypes.assertThat(org.assertj.core.api.AssertionsForInterfaceTypes.assertThat) DataLoader(org.dataloader.DataLoader) Book(org.springframework.graphql.Book) BookSource(org.springframework.graphql.BookSource) GraphQLContext(graphql.GraphQLContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.jupiter.api.Test)

Example 2 with GraphQLContext

use of graphql.GraphQLContext in project micronaut-graphql by micronaut-projects.

the class LoginDataFetcher method get.

@Override
public LoginPayload get(DataFetchingEnvironment environment) throws Exception {
    GraphQLContext graphQLContext = environment.getContext();
    if (LOGIN_RATE_LIMIT_REMAINING <= 0) {
        addRateLimitHeaders(graphQLContext);
        resetRateLimit();
        return LoginPayload.ofError("Rate Limit Exceeded");
    }
    HttpRequest httpRequest = graphQLContext.get("httpRequest");
    MutableHttpResponse<String> httpResponse = graphQLContext.get("httpResponse");
    String username = environment.getArgument("username");
    String password = environment.getArgument("password");
    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
    LOGIN_RATE_LIMIT_REMAINING--;
    Flux<AuthenticationResponse> authenticationResponseFlowable = Flux.from(authenticator.authenticate(httpRequest, usernamePasswordCredentials));
    return authenticationResponseFlowable.map(authenticationResponse -> {
        addRateLimitHeaders(graphQLContext);
        if (authenticationResponse.isAuthenticated()) {
            eventPublisher.publishEvent(new LoginSuccessfulEvent(authenticationResponse));
            Optional<Cookie> jwtCookie = accessTokenCookie(Authentication.build(username), httpRequest);
            jwtCookie.ifPresent(httpResponse::cookie);
            User user = userRepository.findByUsername(username).orElse(null);
            return LoginPayload.ofUser(user);
        } else {
            eventPublisher.publishEvent(new LoginFailedEvent(authenticationResponse));
            return LoginPayload.ofError(authenticationResponse.getMessage().orElse(null));
        }
    }).blockFirst();
}
Also used : HttpRequest(io.micronaut.http.HttpRequest) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) UsernamePasswordCredentials(io.micronaut.security.authentication.UsernamePasswordCredentials) AccessRefreshToken(io.micronaut.security.token.jwt.render.AccessRefreshToken) Cookie(io.micronaut.http.cookie.Cookie) User(example.domain.User) AccessTokenConfiguration(io.micronaut.security.token.jwt.generator.AccessTokenConfiguration) ApplicationEventPublisher(io.micronaut.context.event.ApplicationEventPublisher) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) Authentication(io.micronaut.security.authentication.Authentication) Singleton(jakarta.inject.Singleton) Random(java.util.Random) CookieConfiguration(io.micronaut.http.cookie.CookieConfiguration) AccessRefreshTokenGenerator(io.micronaut.security.token.jwt.generator.AccessRefreshTokenGenerator) UserRepository(example.repository.UserRepository) Authenticator(io.micronaut.security.authentication.Authenticator) Flux(reactor.core.publisher.Flux) LoginSuccessfulEvent(io.micronaut.security.event.LoginSuccessfulEvent) GraphQLContext(graphql.GraphQLContext) DataFetcher(graphql.schema.DataFetcher) TemporalAmount(java.time.temporal.TemporalAmount) Optional(java.util.Optional) HttpRequest(io.micronaut.http.HttpRequest) LoginFailedEvent(io.micronaut.security.event.LoginFailedEvent) AuthenticationResponse(io.micronaut.security.authentication.AuthenticationResponse) User(example.domain.User) Optional(java.util.Optional) GraphQLContext(graphql.GraphQLContext) LoginSuccessfulEvent(io.micronaut.security.event.LoginSuccessfulEvent) AuthenticationResponse(io.micronaut.security.authentication.AuthenticationResponse) LoginFailedEvent(io.micronaut.security.event.LoginFailedEvent) UsernamePasswordCredentials(io.micronaut.security.authentication.UsernamePasswordCredentials)

Example 3 with GraphQLContext

use of graphql.GraphQLContext in project micronaut-graphql by micronaut-projects.

the class RequestResponseCustomizer method customize.

@Override
public Publisher<ExecutionInput> customize(ExecutionInput executionInput, HttpRequest httpRequest, @Nullable MutableHttpResponse<String> httpResponse) {
    GraphQLContext graphQLContext = (GraphQLContext) executionInput.getContext();
    graphQLContext.put("httpRequest", httpRequest);
    graphQLContext.put("httpResponse", httpResponse);
    return Publishers.just(executionInput);
}
Also used : GraphQLContext(graphql.GraphQLContext)

Example 4 with GraphQLContext

use of graphql.GraphQLContext in project graphql-java by graphql-java.

the class ConcernsExamples method contextHelper.

private void contextHelper() {
    // 
    // this could be code that authorises the user in some way and sets up enough context
    // that can be used later inside data fetchers allowing them
    // to do their job
    // 
    UserContext contextForUser = YourGraphqlContextBuilder.getContextForUser(getCurrentUser());
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().graphQLContext(context -> context.put("userContext", contextForUser)).build();
    ExecutionResult executionResult = graphQL.execute(executionInput);
    // ...
    // 
    // later you are able to use this context object when a data fetcher is invoked
    // 
    DataFetcher dataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            UserContext userCtx = environment.getGraphQlContext().get("userContext");
            Long businessObjId = environment.getArgument("businessObjId");
            return invokeBusinessLayerMethod(userCtx, businessObjId);
        }
    };
}
Also used : ExecutionInput(graphql.ExecutionInput) ExecutionResult(graphql.ExecutionResult) StarWarsSchema.queryType(graphql.StarWarsSchema.queryType) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) GraphQL(graphql.GraphQL) GraphQLContext(graphql.GraphQLContext) DataFetcher(graphql.schema.DataFetcher) GraphQLSchema(graphql.schema.GraphQLSchema) ConcurrentMap(java.util.concurrent.ConcurrentMap) ExecutionResult(graphql.ExecutionResult) ExecutionInput(graphql.ExecutionInput) DataFetcher(graphql.schema.DataFetcher) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment)

Example 5 with GraphQLContext

use of graphql.GraphQLContext in project spring-graphql by spring-projects.

the class ContextValueMethodArgumentResolverTests method resolveOptional.

@Test
@SuppressWarnings({ "unchecked", "ConstantConditions", "OptionalGetWithoutIsPresent" })
void resolveOptional() {
    GraphQLContext context = GraphQLContext.newContext().of("optionalBook", this.book).build();
    Optional<Book> actual = (Optional<Book>) resolveValue(context, context, 3);
    assertThat(actual.get()).isSameAs(this.book);
}
Also used : Optional(java.util.Optional) Book(org.springframework.graphql.Book) GraphQLContext(graphql.GraphQLContext) Test(org.junit.jupiter.api.Test)

Aggregations

GraphQLContext (graphql.GraphQLContext)11 Test (org.junit.jupiter.api.Test)6 ExecutionInput (graphql.ExecutionInput)4 Book (org.springframework.graphql.Book)4 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)3 Optional (java.util.Optional)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 DataLoaderRegistry (org.dataloader.DataLoaderRegistry)3 Flux (reactor.core.publisher.Flux)3 Mono (reactor.core.publisher.Mono)3 GraphQL (graphql.GraphQL)2 DataFetcher (graphql.schema.DataFetcher)2 Map (java.util.Map)2 Function (java.util.function.Function)2 AssertionsForInterfaceTypes.assertThat (org.assertj.core.api.AssertionsForInterfaceTypes.assertThat)2 DataLoader (org.dataloader.DataLoader)2 NoOpStatisticsCollector (org.dataloader.stats.NoOpStatisticsCollector)2 StatisticsCollector (org.dataloader.stats.StatisticsCollector)2 BookSource (org.springframework.graphql.BookSource)2 RequestInput (org.springframework.graphql.RequestInput)2