Search in sources :

Example 1 with GraphQLRequest

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);
    }
}
Also used : ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Request(okhttp3.Request) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) ApiException(com.amplifyframework.api.ApiException)

Example 2 with GraphQLRequest

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);
}
Also used : Arrays(java.util.Arrays) Single(io.reactivex.rxjava3.core.Single) SyncConfigurator(com.amplifyframework.datastore.appsync.AppSyncMocking.SyncConfigurator) AmplifyException(com.amplifyframework.AmplifyException) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test) Completable(io.reactivex.rxjava3.core.Completable) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) Observable(io.reactivex.rxjava3.core.Observable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) Temporal(com.amplifyframework.core.model.temporal.Temporal) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) NoOpAction(com.amplifyframework.core.NoOpAction) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) Collections(java.util.Collections) Before(org.junit.Before) Mockito.mock(org.mockito.Mockito.mock) DataStoreException(com.amplifyframework.datastore.DataStoreException) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 3 with GraphQLRequest

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);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) DataStoreException(com.amplifyframework.datastore.DataStoreException) Type(java.lang.reflect.Type) Consumer(com.amplifyframework.core.Consumer) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 4 with GraphQLRequest

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);
}
Also used : GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Temporal(com.amplifyframework.core.model.temporal.Temporal) Consumer(com.amplifyframework.core.Consumer) Meeting(com.amplifyframework.testmodels.meeting.Meeting) Test(org.junit.Test)

Example 5 with GraphQLRequest

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);
}
Also used : Item(com.amplifyframework.testmodels.ecommerce.Item) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Temporal(com.amplifyframework.core.model.temporal.Temporal) Consumer(com.amplifyframework.core.Consumer) Test(org.junit.Test)

Aggregations

GraphQLRequest (com.amplifyframework.api.graphql.GraphQLRequest)10 Consumer (com.amplifyframework.core.Consumer)9 PaginatedResult (com.amplifyframework.api.graphql.PaginatedResult)7 ModelSchema (com.amplifyframework.core.model.ModelSchema)7 ApiException (com.amplifyframework.api.ApiException)6 DataStoreException (com.amplifyframework.datastore.DataStoreException)6 AmplifyException (com.amplifyframework.AmplifyException)5 GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)5 Test (org.junit.Test)5 NonNull (androidx.annotation.NonNull)4 Amplify (com.amplifyframework.core.Amplify)4 Nullable (androidx.annotation.Nullable)3 ApiCategoryBehavior (com.amplifyframework.api.ApiCategoryBehavior)3 AuthModeStrategyType (com.amplifyframework.api.aws.AuthModeStrategyType)3 GraphQLBehavior (com.amplifyframework.api.graphql.GraphQLBehavior)3 SubscriptionType (com.amplifyframework.api.graphql.SubscriptionType)3 Action (com.amplifyframework.core.Action)3 Cancelable (com.amplifyframework.core.async.Cancelable)3 NoOpCancelable (com.amplifyframework.core.async.NoOpCancelable)3 Model (com.amplifyframework.core.model.Model)3