Search in sources :

Example 46 with ModelSchema

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

Example 47 with ModelSchema

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;
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelField(com.amplifyframework.core.model.ModelField) SQLiteColumn(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn) ArrayList(java.util.ArrayList) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable)

Example 48 with ModelSchema

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&lt;T&gt; 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);
}
Also used : DataStoreConfigurationProvider(com.amplifyframework.datastore.DataStoreConfigurationProvider) Single(io.reactivex.rxjava3.core.Single) DataStoreErrorHandler(com.amplifyframework.datastore.DataStoreErrorHandler) BehaviorProcessor(io.reactivex.rxjava3.processors.BehaviorProcessor) NonNull(androidx.annotation.NonNull) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) ModelProvider(com.amplifyframework.core.model.ModelProvider) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) AppSync(com.amplifyframework.datastore.appsync.AppSync) SyncQueriesStartedEvent(com.amplifyframework.datastore.events.SyncQueriesStartedEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) ApiException(com.amplifyframework.api.ApiException) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Time(com.amplifyframework.util.Time) Schedulers(io.reactivex.rxjava3.schedulers.Schedulers) Consumer(com.amplifyframework.core.Consumer) ModelSchema(com.amplifyframework.core.model.ModelSchema) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) HubEvent(com.amplifyframework.hub.HubEvent) Amplify(com.amplifyframework.core.Amplify) Flowable(io.reactivex.rxjava3.core.Flowable) HubChannel(com.amplifyframework.hub.HubChannel) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) Completable(io.reactivex.rxjava3.core.Completable) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) AmplifyDisposables(com.amplifyframework.datastore.AmplifyDisposables) ForEach(com.amplifyframework.util.ForEach) Collections(java.util.Collections) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 49 with ModelSchema

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));
    });
}
Also used : DataStoreConfigurationProvider(com.amplifyframework.datastore.DataStoreConfigurationProvider) Single(io.reactivex.rxjava3.core.Single) DataStoreErrorHandler(com.amplifyframework.datastore.DataStoreErrorHandler) BehaviorProcessor(io.reactivex.rxjava3.processors.BehaviorProcessor) NonNull(androidx.annotation.NonNull) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) ModelProvider(com.amplifyframework.core.model.ModelProvider) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) AppSync(com.amplifyframework.datastore.appsync.AppSync) SyncQueriesStartedEvent(com.amplifyframework.datastore.events.SyncQueriesStartedEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) ApiException(com.amplifyframework.api.ApiException) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Time(com.amplifyframework.util.Time) Schedulers(io.reactivex.rxjava3.schedulers.Schedulers) Consumer(com.amplifyframework.core.Consumer) ModelSchema(com.amplifyframework.core.model.ModelSchema) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) HubEvent(com.amplifyframework.hub.HubEvent) Amplify(com.amplifyframework.core.Amplify) Flowable(io.reactivex.rxjava3.core.Flowable) HubChannel(com.amplifyframework.hub.HubChannel) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) Completable(io.reactivex.rxjava3.core.Completable) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) AmplifyDisposables(com.amplifyframework.datastore.AmplifyDisposables) ForEach(com.amplifyframework.util.ForEach) Collections(java.util.Collections) ModelSchema(com.amplifyframework.core.model.ModelSchema) Completable(io.reactivex.rxjava3.core.Completable) ArrayList(java.util.ArrayList) SyncQueriesStartedEvent(com.amplifyframework.datastore.events.SyncQueriesStartedEvent)

Example 50 with ModelSchema

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));
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema)

Aggregations

ModelSchema (com.amplifyframework.core.model.ModelSchema)109 Test (org.junit.Test)69 SerializedModel (com.amplifyframework.core.model.SerializedModel)34 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)30 Model (com.amplifyframework.core.model.Model)28 DataStoreException (com.amplifyframework.datastore.DataStoreException)26 HashMap (java.util.HashMap)23 ArrayList (java.util.ArrayList)22 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)21 AmplifyException (com.amplifyframework.AmplifyException)19 Consumer (com.amplifyframework.core.Consumer)19 List (java.util.List)17 NonNull (androidx.annotation.NonNull)14 Cancelable (com.amplifyframework.core.async.Cancelable)14 TimeUnit (java.util.concurrent.TimeUnit)14 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)13 Action (com.amplifyframework.core.Action)12 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)12 Collections (java.util.Collections)12 ModelProvider (com.amplifyframework.core.model.ModelProvider)11