use of com.amplifyframework.core.model.ModelSchema 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);
}
use of com.amplifyframework.core.model.ModelSchema in project amplify-android by aws-amplify.
the class SQLiteCommandFactory method extractFieldValues.
// extract model field values to save in database
private List<Object> extractFieldValues(@NonNull Model model) throws DataStoreException {
final String modelName = model.getModelName();
final ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(modelName);
final SQLiteTable table = SQLiteTable.fromSchema(schema);
final SQLiteModelFieldTypeConverter converter = new SQLiteModelFieldTypeConverter(schema, schemaRegistry, gson);
final Map<String, ModelField> modelFields = schema.getFields();
final List<Object> bindings = new ArrayList<>();
for (SQLiteColumn column : table.getSortedColumns()) {
final ModelField modelField = Objects.requireNonNull(modelFields.get(column.getFieldName()));
final Object fieldValue = converter.convertValueFromTarget(model, modelField);
bindings.add(fieldValue);
}
return bindings;
}
use of com.amplifyframework.core.model.ModelSchema 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.core.model.ModelSchema in project amplify-android by aws-amplify.
the class SyncProcessor method hydrate.
/**
* The task of hydrating the DataStore either succeeds (with no return value),
* or it fails, with an explanation.
* @return An Rx {@link Completable} which can be used to perform the operation.
*/
Completable hydrate() {
final List<Completable> hydrationTasks = new ArrayList<>();
List<ModelSchema> modelSchemas = new ArrayList<>(modelProvider.modelSchemas().values());
// And sort them all, according to their model's topological order,
// So that when we save them, the references will exist.
TopologicalOrdering ordering = TopologicalOrdering.forRegisteredModels(schemaRegistry, modelProvider);
Collections.sort(modelSchemas, ordering::compare);
for (ModelSchema schema : modelSchemas) {
hydrationTasks.add(createHydrationTask(schema));
}
return Completable.concat(hydrationTasks).doOnSubscribe(ignore -> {
// This is where we trigger the syncQueriesStarted event since
// doOnSubscribe means that all upstream hydration tasks
// have started.
Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(DataStoreChannelEventName.SYNC_QUERIES_STARTED, new SyncQueriesStartedEvent(modelNames)));
}).doOnComplete(() -> {
// When the Completable completes, then emit syncQueriesReady.
Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(DataStoreChannelEventName.SYNC_QUERIES_READY));
});
}
use of com.amplifyframework.core.model.ModelSchema in project amplify-android by aws-amplify.
the class MutationProcessor method create.
// For an item in the outbox, dispatch a create mutation
private <T extends Model> Single<ModelWithMetadata<T>> create(PendingMutation<T> mutation) {
final T createdItem = mutation.getMutatedItem();
final ModelSchema createdItemSchema = this.schemaRegistry.getModelSchemaForModelClass(createdItem.getModelName());
return publishWithStrategy(mutation, (model, onSuccess, onError) -> appSync.create(model, createdItemSchema, onSuccess, onError));
}
Aggregations