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