use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class SubscriptionEndpoint method requestSubscription.
synchronized <T> void requestSubscription(@NonNull GraphQLRequest<T> request, @NonNull AuthorizationType authType, @NonNull Consumer<String> onSubscriptionStarted, @NonNull Consumer<GraphQLResponse<T>> onNextItem, @NonNull Consumer<ApiException> onSubscriptionError, @NonNull Action onSubscriptionComplete) {
Objects.requireNonNull(request);
Objects.requireNonNull(onSubscriptionStarted);
Objects.requireNonNull(onNextItem);
Objects.requireNonNull(onSubscriptionError);
Objects.requireNonNull(onSubscriptionComplete);
// force a new connection to be created.
if (webSocketListener == null || webSocketListener.isDisconnectedState()) {
webSocketListener = new AmplifyWebSocketListener();
try {
webSocket = okHttpClient.newWebSocket(new Request.Builder().url(buildConnectionRequestUrl(authType)).addHeader("Sec-WebSocket-Protocol", "graphql-ws").build(), webSocketListener);
} catch (ApiException apiException) {
onSubscriptionError.accept(apiException);
return;
}
}
final String subscriptionId = UUID.randomUUID().toString();
pendingSubscriptionIds.add(subscriptionId);
// Every request waits here for the connection to be ready.
Connection connection = webSocketListener.waitForConnectionReady();
if (connection.hasFailure()) {
// If the latch didn't count all the way down
if (pendingSubscriptionIds.remove(subscriptionId)) {
// The subscription was pending, so we need to emit an error.
onSubscriptionError.accept(new ApiException(connection.getFailureReason(), AmplifyException.TODO_RECOVERY_SUGGESTION));
return;
}
}
try {
webSocket.send(new JSONObject().put("id", subscriptionId).put("type", "start").put("payload", new JSONObject().put("data", request.getContent()).put("extensions", new JSONObject().put("authorization", authorizer.createHeadersForSubscription(request, authType)))).toString());
} catch (JSONException | ApiException exception) {
// If the subscriptionId was still pending, then we can call the onSubscriptionError
if (pendingSubscriptionIds.remove(subscriptionId)) {
if (exception instanceof ApiAuthException) {
// Don't wrap it if it's an ApiAuthException.
onSubscriptionError.accept((ApiAuthException) exception);
} else {
onSubscriptionError.accept(new ApiException("Failed to construct subscription registration message.", exception, AmplifyException.TODO_RECOVERY_SUGGESTION));
}
}
return;
}
Subscription<T> subscription = new Subscription<>(onNextItem, onSubscriptionError, onSubscriptionComplete, responseFactory, request.getResponseType(), request);
subscriptions.put(subscriptionId, subscription);
if (subscription.awaitSubscriptionReady()) {
pendingSubscriptionIds.remove(subscriptionId);
onSubscriptionStarted.accept(subscriptionId);
}
}
use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class AppSyncMockingTest method mockFailureForSync.
/**
* When mockFailure() is called on the SyncConfigurator, the AppSync mock
* will emit the provided failure.
* @throws DataStoreException On failure to get a SyncConfigurator via sync()
*/
@Test
public void mockFailureForSync() throws DataStoreException {
DataStoreException failure = new DataStoreException("Foo", "Bar");
AppSyncMocking.sync(appSync).mockFailure(failure);
GraphQLRequest<PaginatedResult<ModelWithMetadata<BlogOwner>>> request = appSync.buildSyncRequest(schema, null, 100, QueryPredicates.all());
Single.create(emitter -> appSync.sync(request, emitter::onSuccess, emitter::onError)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS).assertError(failure);
}
use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class AppSyncClientTest method validateBaseSyncQueryGen.
/**
* Validates the construction of a base-sync query.
* @throws JSONException On bad request JSON found in API category call
* @throws DataStoreException If no valid response returned from AppSync endpoint during sync
* @throws AmplifyException On failure to arrange model schema
*/
@Test
public void validateBaseSyncQueryGen() throws JSONException, AmplifyException {
ModelSchema schema = ModelSchema.fromModelClass(BlogOwner.class);
Await.result((Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<BlogOwner>>>> onResult, Consumer<DataStoreException> onError) -> {
try {
GraphQLRequest<PaginatedResult<ModelWithMetadata<BlogOwner>>> request = endpoint.buildSyncRequest(schema, null, null, QueryPredicates.all());
endpoint.sync(request, onResult, onError);
} catch (DataStoreException datastoreException) {
onError.accept(datastoreException);
}
});
// Now, capture the request argument on API, so we can see what was passed.
// Recall that we pass a raw doc to API.
ArgumentCaptor<GraphQLRequest<ModelWithMetadata<BlogOwner>>> requestCaptor = ArgumentCaptor.forClass(GraphQLRequest.class);
verify(api).query(requestCaptor.capture(), any(Consumer.class), any(Consumer.class));
GraphQLRequest<ModelWithMetadata<BlogOwner>> capturedRequest = requestCaptor.getValue();
Type type = TypeMaker.getParameterizedType(PaginatedResult.class, ModelWithMetadata.class, BlogOwner.class);
assertEquals(type, capturedRequest.getResponseType());
// The request was sent as JSON. It has a null variables field, and a present query field.
JSONAssert.assertEquals(Resources.readAsString("base-sync-request-document-for-blog-owner.txt"), capturedRequest.getContent(), true);
}
use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class AppSyncClientTest method validateUpdateMutationWithDates.
/**
* Validates date serialization when creating mutation.
* @throws JSONException from JSONAssert.assertEquals JSON parsing error
* @throws AmplifyException from ModelSchema.fromModelClass to convert model to schema
*/
@Test
public void validateUpdateMutationWithDates() throws JSONException, AmplifyException {
// Act: build a mutation to create a Meeting
final Meeting meeting = Meeting.builder().name("meeting1").id("45a5f600-8aa8-41ac-a529-aed75036f5be").date(new Temporal.Date("2001-02-03")).dateTime(new Temporal.DateTime("2001-02-03T01:30:15Z")).time(new Temporal.Time("01:22:33")).timestamp(new Temporal.Timestamp(1234567890000L, TimeUnit.MILLISECONDS)).build();
endpoint.update(meeting, ModelSchema.fromModelClass(Meeting.class), 1, response -> {
}, error -> {
});
// Now, capture the request argument on API, so we can see what was passed.
ArgumentCaptor<GraphQLRequest<ModelWithMetadata<Meeting>>> requestCaptor = ArgumentCaptor.forClass(GraphQLRequest.class);
verify(api).mutate(requestCaptor.capture(), any(Consumer.class), any(Consumer.class));
GraphQLRequest<ModelWithMetadata<Meeting>> capturedRequest = requestCaptor.getValue();
// Assert
assertEquals(TypeMaker.getParameterizedType(ModelWithMetadata.class, Meeting.class), capturedRequest.getResponseType());
JSONAssert.assertEquals(Resources.readAsString("update-meeting.txt"), capturedRequest.getContent(), true);
}
use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class AppSyncClientTest method validateDeleteMutationWithCustomPrimaryKey.
/**
* Validates delete mutation for item with custom primary key.
* @throws JSONException from JSONAssert.assertEquals JSON parsing error
* @throws AmplifyException from ModelSchema.fromModelClass to convert model to schema
*/
@Test
public void validateDeleteMutationWithCustomPrimaryKey() throws AmplifyException, JSONException {
final Item item = Item.builder().orderId("123a7asa").status(Status.IN_TRANSIT).createdAt(new Temporal.DateTime("2021-04-20T15:20:32.651Z")).name("Gummy Bears").build();
ModelSchema schema = ModelSchema.fromModelClass(Item.class);
endpoint.delete(item, schema, 1, response -> {
}, error -> {
});
// Now, capture the request argument on API, so we can see what was passed.
ArgumentCaptor<GraphQLRequest<ModelWithMetadata<Item>>> requestCaptor = ArgumentCaptor.forClass(GraphQLRequest.class);
verify(api).mutate(requestCaptor.capture(), any(Consumer.class), any(Consumer.class));
GraphQLRequest<ModelWithMetadata<Item>> capturedRequest = requestCaptor.getValue();
// Assert
assertEquals(TypeMaker.getParameterizedType(ModelWithMetadata.class, Item.class), capturedRequest.getResponseType());
JSONAssert.assertEquals(Resources.readAsString("delete-item.txt"), capturedRequest.getContent(), true);
}
Aggregations