Search in sources :

Example 26 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class AppSyncClient method sync.

@NonNull
@Override
public <T extends Model> Cancelable sync(@NonNull GraphQLRequest<PaginatedResult<ModelWithMetadata<T>>> request, @NonNull Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<T>>>> onResponse, @NonNull Consumer<DataStoreException> onFailure) {
    final Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<T>>>> responseConsumer = apiQueryResponse -> {
        if (apiQueryResponse.hasErrors()) {
            onFailure.accept(new DataStoreException("Failure performing sync query to AppSync: " + apiQueryResponse.getErrors().toString(), AmplifyException.TODO_RECOVERY_SUGGESTION));
        } else {
            onResponse.accept(apiQueryResponse);
        }
    };
    final Consumer<ApiException> failureConsumer = failure -> onFailure.accept(new DataStoreException("Failure performing sync query to AppSync.", failure, AmplifyException.TODO_RECOVERY_SUGGESTION));
    final Cancelable cancelable = api.query(request, responseConsumer, failureConsumer);
    if (cancelable != null) {
        return cancelable;
    }
    return new NoOpCancelable();
}
Also used : Amplify(com.amplifyframework.core.Amplify) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Model(com.amplifyframework.core.model.Model) Action(com.amplifyframework.core.Action) ApiException(com.amplifyframework.api.ApiException) Logger(com.amplifyframework.logging.Logger) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) Nullable(androidx.annotation.Nullable) Cancelable(com.amplifyframework.core.async.Cancelable) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthModeStrategyType(com.amplifyframework.api.aws.AuthModeStrategyType) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiCategoryBehavior(com.amplifyframework.api.ApiCategoryBehavior) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) DataStoreException(com.amplifyframework.datastore.DataStoreException) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) Cancelable(com.amplifyframework.core.async.Cancelable) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ApiException(com.amplifyframework.api.ApiException) NonNull(androidx.annotation.NonNull)

Example 27 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class AppSyncClient method subscription.

private <T extends Model> Cancelable subscription(SubscriptionType subscriptionType, ModelSchema modelSchema, Consumer<String> onSubscriptionStarted, Consumer<GraphQLResponse<ModelWithMetadata<T>>> onNextResponse, Consumer<DataStoreException> onSubscriptionFailure, Action onSubscriptionCompleted) {
    final GraphQLRequest<ModelWithMetadata<T>> request;
    try {
        request = AppSyncRequestFactory.buildSubscriptionRequest(modelSchema, subscriptionType, authModeStrategyType);
    } catch (DataStoreException requestGenerationException) {
        onSubscriptionFailure.accept(requestGenerationException);
        return new NoOpCancelable();
    }
    final Consumer<GraphQLResponse<ModelWithMetadata<T>>> responseConsumer = response -> {
        if (response.hasErrors()) {
            onSubscriptionFailure.accept(new DataStoreException.GraphQLResponseException("Subscription error for " + modelSchema.getName() + ": " + response.getErrors(), response.getErrors()));
        } else {
            onNextResponse.accept(response);
        }
    };
    final Consumer<ApiException> failureConsumer = failure -> onSubscriptionFailure.accept(new DataStoreException("Error during subscription.", failure, "Evaluate details."));
    final Cancelable cancelable = api.subscribe(request, onSubscriptionStarted, responseConsumer, failureConsumer, onSubscriptionCompleted);
    if (cancelable != null) {
        return cancelable;
    }
    return new NoOpCancelable();
}
Also used : Amplify(com.amplifyframework.core.Amplify) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Model(com.amplifyframework.core.model.Model) Action(com.amplifyframework.core.Action) ApiException(com.amplifyframework.api.ApiException) Logger(com.amplifyframework.logging.Logger) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) Nullable(androidx.annotation.Nullable) Cancelable(com.amplifyframework.core.async.Cancelable) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthModeStrategyType(com.amplifyframework.api.aws.AuthModeStrategyType) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiCategoryBehavior(com.amplifyframework.api.ApiCategoryBehavior) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) DataStoreException(com.amplifyframework.datastore.DataStoreException) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) Cancelable(com.amplifyframework.core.async.Cancelable) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ApiException(com.amplifyframework.api.ApiException)

Example 28 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class RxApiBindingTest method subscribeStartsAndGetsCancelled.

/**
 * Verify that the subscription starts and is cancelled gracefully.
 * @throws InterruptedException Not expected.
 */
@SuppressWarnings("rawtypes")
@Test
public void subscribeStartsAndGetsCancelled() throws InterruptedException {
    // Arrange a category behavior which emits an expected sequence of callback events
    String token = RandomString.string();
    GraphQLRequest<Model> request = createMockSubscriptionRequest(Model.class);
    ConnectionStateEvent expectedConnectionStateEvent = new ConnectionStateEvent(ConnectionState.CONNECTED, token);
    doAnswer(invocation -> {
        final int onStartPosition = 1;
        final int onCompletePosition = 4;
        Consumer<String> onStart = invocation.getArgument(onStartPosition);
        Action onComplete = invocation.getArgument(onCompletePosition);
        onStart.accept(token);
        GraphQLOperation mockApiOperation = mock(GraphQLOperation.class);
        doAnswer(apiCancelInvocation -> {
            onComplete.call();
            return null;
        }).when(mockApiOperation).cancel();
        return mockApiOperation;
    }).when(delegate).subscribe(eq(request), anyConsumer(), anyConsumer(), anyConsumer(), anyAction());
    // Act: subscribe via binding
    RxSubscriptionOperation<GraphQLResponse<Model>> rxOperation = rxApi.subscribe(request);
    // Act: subscribe via binding
    TestObserver<GraphQLResponse<Model>> dataObserver = rxOperation.observeSubscriptionData().test();
    TestObserver<ConnectionStateEvent> startObserver = rxOperation.observeConnectionState().test();
    startObserver.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    startObserver.assertValue(expectedConnectionStateEvent);
    startObserver.assertNoErrors();
    // Act: cancel the subscription
    Completable.timer(1, TimeUnit.SECONDS).andThen(Completable.fromAction(rxOperation::cancel)).subscribe();
    dataObserver.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    dataObserver.assertNoValues();
    dataObserver.assertNoErrors();
    dataObserver.assertComplete();
    startObserver.assertComplete();
}
Also used : Matchers.anyAction(com.amplifyframework.rx.Matchers.anyAction) Action(com.amplifyframework.core.Action) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) RandomString(com.amplifyframework.testutils.random.RandomString) ConnectionStateEvent(com.amplifyframework.rx.RxOperations.RxSubscriptionOperation.ConnectionStateEvent) GraphQLOperation(com.amplifyframework.api.graphql.GraphQLOperation) RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test)

Example 29 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class RxApiBindingTest method queryEmitsFailure.

/**
 * When the API behavior emits a failure for a query, so too should the Rx binding.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void queryEmitsFailure() throws InterruptedException {
    // Arrange: category behavior emits a failure
    ApiException expectedFailure = new ApiException("Expected", "Failure");
    GraphQLRequest<Iterable<Model>> listRequest = createMockListRequest(Model.class);
    doAnswer(invocation -> {
        // 0 = clazz, 1 = onResponse, 2 = onFailure
        final int positionOfOnFailure = 2;
        Consumer<ApiException> onFailure = invocation.getArgument(positionOfOnFailure);
        onFailure.accept(expectedFailure);
        return null;
    }).when(delegate).query(eq(listRequest), anyConsumer(), anyConsumer());
    // Act: access query() method via Rx binding
    TestObserver<GraphQLResponse<Iterable<Model>>> observer = rxApi.query(listRequest).test();
    // Assert: failure bubbles up to Rx
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertError(expectedFailure);
    verify(delegate).query(eq(listRequest), anyConsumer(), anyConsumer());
}
Also used : RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 30 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class GsonGraphQLResponseFactoryTest method partialResponseRendersWithTodoDataAndErrors.

/**
 * Validates that the converter is able to parse a partial GraphQL
 * response into a result. In this case, the result contains some
 * data, but also a list of errors.
 * @throws ApiException From API configuration
 */
@Test
public void partialResponseRendersWithTodoDataAndErrors() throws ApiException {
    // Arrange some JSON string from a "server"
    final String partialResponseJson = Resources.readAsString("partial-gql-response.json");
    // Act! Parse it into a model.
    Type responseType = TypeMaker.getParameterizedType(PaginatedResult.class, Todo.class);
    GraphQLRequest<PaginatedResult<Todo>> request = buildDummyRequest(responseType);
    final GraphQLResponse<PaginatedResult<Todo>> response = responseFactory.buildResponse(request, partialResponseJson);
    // Assert that the model contained things...
    assertNotNull(response);
    assertNotNull(response.getData());
    assertNotNull(response.getData().getItems());
    // Assert that all of the fields of the different todos
    // match what we would expect from a manual inspection of the
    // JSON.
    final Iterable<Todo> actualTodos = response.getData().getItems();
    final List<Todo> expectedTodos = Arrays.asList(Todo.builder().id("fa1c21cc-0458-4bca-bcb1-101579fb85c7").name(null).description("Test").build(), Todo.builder().id("68bad242-dec5-415b-acb3-daee3b069ce5").name(null).description("Test").build(), Todo.builder().id("f64e2e9a-42ad-4455-b8ee-d1cfae7e9f01").name(null).description("Test").build());
    assertEquals(expectedTodos, actualTodos);
    // Assert that we parsed the errors successfully.
    assertNotNull(response.getErrors());
    final List<GraphQLResponse.Error> expectedErrors = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        String message = "failed";
        List<GraphQLLocation> locations = Collections.singletonList(new GraphQLLocation(5, 7));
        List<GraphQLPathSegment> path = Arrays.asList(new GraphQLPathSegment("listTodos"), new GraphQLPathSegment("items"), new GraphQLPathSegment(i), new GraphQLPathSegment("name"));
        Map<String, Object> extensions = new HashMap<>();
        extensions.put("errorType", null);
        extensions.put("errorInfo", null);
        extensions.put("data", null);
        expectedErrors.add(new GraphQLResponse.Error(message, locations, path, extensions));
    }
    assertEquals(expectedErrors, response.getErrors());
}
Also used : GraphQLLocation(com.amplifyframework.api.graphql.GraphQLLocation) HashMap(java.util.HashMap) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) ArrayList(java.util.ArrayList) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) GraphQLPathSegment(com.amplifyframework.api.graphql.GraphQLPathSegment) QueryType(com.amplifyframework.api.graphql.QueryType) Type(java.lang.reflect.Type) JSONObject(org.json.JSONObject) Test(org.junit.Test)

Aggregations

GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)30 Test (org.junit.Test)23 PaginatedResult (com.amplifyframework.api.graphql.PaginatedResult)14 Model (com.amplifyframework.core.model.Model)11 ApiException (com.amplifyframework.api.ApiException)10 Action (com.amplifyframework.core.Action)9 Consumer (com.amplifyframework.core.Consumer)9 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)9 JSONObject (org.json.JSONObject)9 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)8 GraphQLRequest (com.amplifyframework.api.graphql.GraphQLRequest)7 RandomString (com.amplifyframework.testutils.random.RandomString)7 AmplifyException (com.amplifyframework.AmplifyException)6 ModelSchema (com.amplifyframework.core.model.ModelSchema)6 ModelMetadata (com.amplifyframework.datastore.appsync.ModelMetadata)6 RandomModel (com.amplifyframework.testutils.random.RandomModel)6 HashMap (java.util.HashMap)6 QueryType (com.amplifyframework.api.graphql.QueryType)5 SubscriptionType (com.amplifyframework.api.graphql.SubscriptionType)5 Cancelable (com.amplifyframework.core.async.Cancelable)5