use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class SyncProcessor method syncModel.
/**
* Sync models for a given model class.
* This involves three steps:
* 1. Lookup the last time the model class was synced;
* 2. Make a request to the AppSync endpoint. If the last sync time is within a recent window
* of time, then request a *delta* sync. If the last sync time is outside a recent window of time,
* perform a *base* sync. A base sync is preformed by passing null.
* 3. Continue fetching paged results until !hasNextResult() or we have synced the max records.
*
* @param schema The schema of the model to sync
* @param syncTime The time of a last successful sync.
* @param <T> The type of model to sync.
* @return a stream of all ModelWithMetadata<T> objects from all pages for the provided model.
* @throws DataStoreException if dataStoreConfigurationProvider.getConfiguration() fails
*/
private <T extends Model> Flowable<List<ModelWithMetadata<T>>> syncModel(ModelSchema schema, SyncTime syncTime) throws DataStoreException {
final Long lastSyncTimeAsLong = syncTime.exists() ? syncTime.toLong() : null;
final Integer syncPageSize = dataStoreConfigurationProvider.getConfiguration().getSyncPageSize();
final Integer syncMaxRecords = dataStoreConfigurationProvider.getConfiguration().getSyncMaxRecords();
AtomicReference<Integer> recordsFetched = new AtomicReference<>(0);
QueryPredicate predicate = queryPredicateProvider.getPredicate(schema.getName());
// Create a BehaviorProcessor, and set the default value to a GraphQLRequest that fetches the first page.
BehaviorProcessor<GraphQLRequest<PaginatedResult<ModelWithMetadata<T>>>> processor = BehaviorProcessor.createDefault(appSync.buildSyncRequest(schema, lastSyncTimeAsLong, syncPageSize, predicate));
return processor.concatMap(request -> {
if (isSyncRetryEnabled) {
return syncPageWithRetry(request).toFlowable();
} else {
return syncPage(request).toFlowable();
}
}).doOnNext(paginatedResult -> {
if (paginatedResult.hasNextResult()) {
processor.onNext(paginatedResult.getRequestForNextResult());
} else {
processor.onComplete();
}
}).map(paginatedResult -> Flowable.fromIterable(paginatedResult).map(modelWithMetadata -> hydrateSchemaIfNeeded(modelWithMetadata, schema)).toList().blockingGet()).takeUntil(items -> recordsFetched.accumulateAndGet(items.size(), Integer::sum) >= syncMaxRecords);
}
use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class AWSApiPluginTest method graphQlMutationGetsResponse.
/**
* It should be possible to perform a successful call to
* {@link AWSApiPlugin#mutate(GraphQLRequest, Consumer, Consumer)}.
* When the server returns a valid response, then the mutate methods should
* emit content via their value consumer.
* @throws ApiException If call to mutate(...) itself emits such an exception
* @throws JSONException On failure to arrange response JSON
*/
@Test
public void graphQlMutationGetsResponse() throws JSONException, ApiException {
HubAccumulator networkStatusObserver = HubAccumulator.create(HubChannel.API, ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, 1).start();
// Arrange a response from the "server"
String expectedName = RandomString.string();
webServer.enqueue(new MockResponse().setBody(new JSONObject().put("data", new JSONObject().put("createBlogOwner", new JSONObject().put("name", expectedName))).toString()));
// Try to perform a mutation.
BlogOwner tony = BlogOwner.builder().name(expectedName).build();
GraphQLResponse<BlogOwner> actualResponse = Await.<GraphQLResponse<BlogOwner>, ApiException>result(((onResult, onError) -> plugin.mutate(ModelMutation.create(tony), onResult, onError)));
// Assert that the expected response was received
assertEquals(expectedName, actualResponse.getData().getName());
// Verify that the expected hub event fired.
HubEvent<?> event = networkStatusObserver.awaitFirst();
assertNotNull(event);
assertTrue(event.getData() instanceof ApiEndpointStatusChangeEvent);
ApiEndpointStatusChangeEvent eventData = (ApiEndpointStatusChangeEvent) event.getData();
assertEquals(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, eventData.getCurrentStatus());
}
use of com.amplifyframework.api.graphql.GraphQLRequest in project amplify-android by aws-amplify.
the class AppSyncClient method mutation.
private <T extends Model> Cancelable mutation(final GraphQLRequest<ModelWithMetadata<T>> request, final Consumer<GraphQLResponse<ModelWithMetadata<T>>> onResponse, final Consumer<DataStoreException> onFailure) {
final Consumer<GraphQLResponse<ModelWithMetadata<T>>> responseConsumer = response -> {
if (response.hasErrors()) {
onResponse.accept(new GraphQLResponse<>(null, response.getErrors()));
} else {
onResponse.accept(response);
}
};
final Consumer<ApiException> failureConsumer = failure -> onFailure.accept(new DataStoreException("Failure during mutation.", failure, "Check details."));
final Cancelable cancelable = api.mutate(request, responseConsumer, failureConsumer);
if (cancelable != null) {
return cancelable;
}
return new NoOpCancelable();
}
use of com.amplifyframework.api.graphql.GraphQLRequest 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.GraphQLRequest 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();
}
Aggregations