From 7287849a039d1c3bc779a9e7ab210cd57ddad5b1 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Fri, 20 May 2022 12:53:43 -0700 Subject: [PATCH 01/10] chore(datastore): cleanup the codebase - CRLF to LF - Source code reformatting and fixing linter issues --- .../AmplifyDataStorePlugin.kt | 14 +- .../DataStoreHubEventStreamHandler.kt | 8 +- .../types/hub/FlutterModelSyncedEvent.kt | 8 +- .../types/hub/FlutterNetworkStatusEvent.kt | 2 +- .../types/hub/FlutterSyncMetaData.kt | 2 +- .../hub/FlutterSyncQueriesStartedEvent.kt | 3 +- .../types/model/FlutterModelSchema.kt | 2 +- .../types/model/FlutterSerializedModel.kt | 3 +- .../types/query/QueryOptionsBuilder.kt | 6 +- .../types/query/QueryPredicateBuilder.kt | 2 +- .../AmplifyDataStoreHubTest.kt | 213 +++--- .../AmplifyDataStorePluginTest.kt | 139 ++-- .../AmplifyModelSchemaTest.kt | 42 +- .../AmplifySerializedModelTest.kt | 26 +- .../amplify/amplify_datastore/Latch.kt | 5 +- .../amplify/amplify_datastore/SchemaData.kt | 690 +++++++++--------- .../AmplifyModelSchemaUnitTests.swift | 19 +- .../AmplifySerializedModelUnitTests.swift | 146 ++-- .../DataStoreHubEventStreamHandlerTests.swift | 138 ++-- .../unit_tests/DataStorePluginUnitTests.swift | 142 ++-- .../ios/unit_tests/GetJsonFromFileUtil.swift | 2 +- .../ModelSchemaEquatableExtensions.swift | 17 +- .../unit_tests/QueryPaginationUnitTests.swift | 19 +- .../QueryPredicateBuilderUnitTests.swift | 21 +- .../QuerySortBuilderUnitTests.swift | 17 +- .../FlutterSerializedModelData.swift | 69 +- .../ios/unit_tests/resources/SchemaData.swift | 80 +- .../ios/Classes/DataStoreBridge.swift | 17 +- .../DataStoreHubEventStreamHandler.swift | 63 +- .../DataStoreObserveEventStreamHandler.swift | 7 +- .../ios/Classes/FlutterDataStoreError.swift | 2 +- .../FlutterDataStoreErrorHandler.swift | 14 +- .../FlutterDataStoreErrorMessage.swift | 2 +- .../FlutterDataStoreRequestUtils.swift | 23 +- .../ios/Classes/FlutterSchemaRegistry.swift | 21 +- .../ios/Classes/GetJsonValue.swift | 8 +- .../Classes/SwiftAmplifyDataStorePlugin.swift | 203 +++--- .../Classes/types/hub/FlutterHubElement.swift | 23 +- .../Classes/types/hub/FlutterHubEvent.swift | 4 +- .../types/hub/FlutterModelSyncedEvent.swift | 22 +- .../types/hub/FlutterNetworkStatusEvent.swift | 12 +- .../FlutterOutboxMutationEnqueuedEvent.swift | 19 +- .../FlutterOutboxMutationProcessedEvent.swift | 18 +- .../types/hub/FlutterOutboxStatusEvent.swift | 12 +- .../Classes/types/hub/FlutterReadyEvent.swift | 10 +- ...FlutterSubscriptionsEstablishedEvent.swift | 10 +- .../hub/FlutterSyncQueriesReadyEvent.swift | 10 +- .../hub/FlutterSyncQueriesStartedEvent.swift | 12 +- .../types/hub/FlutterSyncReceivedEvent.swift | 12 +- .../Classes/types/model/FlutterAuthRule.swift | 61 +- .../types/model/FlutterModelAssociation.swift | 37 +- .../types/model/FlutterModelField.swift | 33 +- .../types/model/FlutterModelFieldType.swift | 46 +- .../types/model/FlutterModelSchema.swift | 21 +- .../types/model/FlutterSerializedModel.swift | 61 +- .../model/FlutterSubscriptionEvent.swift | 9 +- .../types/model/ModelSchemaError.swift | 26 +- .../types/query/QueryPaginationBuilder.swift | 7 +- .../types/query/QueryPredicateBuilder.swift | 29 +- .../types/query/QuerySortBuilder.swift | 6 +- .../types/temporal/FlutterTemporal.swift | 10 +- 61 files changed, 1342 insertions(+), 1363 deletions(-) diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt index f349338558..c4f9b21e04 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt @@ -157,7 +157,7 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { ExceptionMessages.missingExceptionMessage, ExceptionMessages.missingRecoverySuggestion, "Received invalid request from Dart, modelSchemas and/or modelProviderVersion" + - " are not available. Request: " + request.toString() + " are not available. Request: " + request.toString() ) ) } @@ -420,7 +420,7 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { dataStoreObserveEventStreamHandler.sendEvent( FlutterSubscriptionEvent( serializedModel = event.item() as SerializedModel, - eventType = event.type().name.toLowerCase(Locale.getDefault()) + eventType = event.type().name.lowercase(Locale.getDefault()) ).toMap() ) } @@ -712,7 +712,7 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { private fun createConflictHandler(request: Map): DataStoreConflictHandler { return if (request["hasConflictHandler"] as? Boolean? == true) { DataStoreConflictHandler { conflictData, - onDecision -> + onDecision -> val modelName = conflictData.local.modelName val args = mapOf( @@ -742,7 +742,11 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { .serializedData((resultMap["customModel"] as Map<*, *>).cast()) .modelSchema(modelProvider.modelSchemas().getValue(modelName)) .build() - onDecision.accept(DataStoreConflictHandler.ConflictResolutionDecision.retry(serializedModel)) + onDecision.accept( + DataStoreConflictHandler.ConflictResolutionDecision.retry( + serializedModel + ) + ) } } } catch (e: Exception) { @@ -766,7 +770,7 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { } } else { DataStoreConflictHandler { _, - onDecision -> + onDecision -> onDecision.accept(DataStoreConflictHandler.ConflictResolutionDecision.applyRemote()) } } diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/DataStoreHubEventStreamHandler.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/DataStoreHubEventStreamHandler.kt index cd9ea24dd9..579e3ec86c 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/DataStoreHubEventStreamHandler.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/DataStoreHubEventStreamHandler.kt @@ -157,7 +157,8 @@ class DataStoreHubEventStreamHandler : EventChannel.StreamHandler { try { val outboxMutationEnqueued = hubEvent.data as OutboxMutationEvent<*> if (outboxMutationEnqueued.element.model is SerializedModel) { - val modelName = (outboxMutationEnqueued.element.model as SerializedModel).modelName as String + val modelName = + (outboxMutationEnqueued.element.model as SerializedModel).modelName as String val res = FlutterOutboxMutationEnqueuedEvent( hubEvent.name, modelName, @@ -213,7 +214,10 @@ class DataStoreHubEventStreamHandler : EventChannel.StreamHandler { LOG.error("Element is not an instance of SerializedModel.") } } catch (e: Exception) { - LOG.error("Failed to parse and send ${DataStoreChannelEventName.SUBSCRIPTION_DATA_PROCESSED} event: ", e) + LOG.error( + "Failed to parse and send ${DataStoreChannelEventName.SUBSCRIPTION_DATA_PROCESSED} event: ", + e + ) } } else -> { diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterModelSyncedEvent.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterModelSyncedEvent.kt index ce7799da1d..617ec3d90f 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterModelSyncedEvent.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterModelSyncedEvent.kt @@ -18,10 +18,10 @@ package com.amazonaws.amplify.amplify_datastore.types.hub class FlutterModelSyncedEvent( override val eventName: String, val model: String, - val isFullSync: Boolean, - val isDeltaSync: Boolean, - val added: Int, - val updated: Int, + private val isFullSync: Boolean, + private val isDeltaSync: Boolean, + private val added: Int, + private val updated: Int, val deleted: Int ) : FlutterHubEvent { override fun toValueMap(): Map { diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterNetworkStatusEvent.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterNetworkStatusEvent.kt index 2aaff80814..45ebe59c39 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterNetworkStatusEvent.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterNetworkStatusEvent.kt @@ -15,7 +15,7 @@ package com.amazonaws.amplify.amplify_datastore.types.hub -class FlutterNetworkStatusEvent(override val eventName: String, val active: Boolean) : FlutterHubEvent { +class FlutterNetworkStatusEvent(override val eventName: String, private val active: Boolean) : FlutterHubEvent { override fun toValueMap(): Map { return mapOf( "eventName" to this.eventName, diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt index 0cdc08e927..e26d117306 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt @@ -18,7 +18,7 @@ package com.amazonaws.amplify.amplify_datastore.types.hub import com.amplifyframework.core.model.Model import com.amplifyframework.datastore.syncengine.OutboxMutationEvent -class FlutterSyncMetaData(var metadata: OutboxMutationEvent.OutboxMutationEventElement) { +class FlutterSyncMetaData(private var metadata: OutboxMutationEvent.OutboxMutationEventElement) { fun toValueMap(): Map { return mapOf( "id" to this.metadata.model.id, diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncQueriesStartedEvent.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncQueriesStartedEvent.kt index f1fe766cd3..77700def22 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncQueriesStartedEvent.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncQueriesStartedEvent.kt @@ -17,7 +17,8 @@ package com.amazonaws.amplify.amplify_datastore.types.hub import org.json.JSONArray -class FlutterSyncQueriesStartedEvent(override val eventName: String, private val models: Array) : FlutterHubEvent { +class FlutterSyncQueriesStartedEvent(override val eventName: String, private val models: Array) : + FlutterHubEvent { override fun toValueMap(): Map { return mapOf( "eventName" to this.eventName, diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt index 03c0d92ac1..cb71c20207 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt @@ -38,7 +38,7 @@ data class FlutterModelSchema(val map: Map) { if (!authRules.isNullOrEmpty()) { builder = builder.authRules(authRules.map { it.convertToNativeAuthRule() }) } - if (!associations.isNullOrEmpty()) { + if (!associations.isEmpty()) { builder = builder.associations( associations.mapValues { it.value.convertToNativeModelAssociation() } ) diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt index 16dd3dbd28..097d4d8f23 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt @@ -31,7 +31,8 @@ data class FlutterSerializedModel(val serializedModel: SerializedModel) { // ignored fields private val id: String = serializedModel.id - private val modelName: String = parseModelName(serializedModel.modelName) // ModelSchema -> SerializedModel should always have a name + private val modelName: String = + parseModelName(serializedModel.modelName) // ModelSchema -> SerializedModel should always have a name fun toMap(): Map { diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryOptionsBuilder.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryOptionsBuilder.kt index a228cd4e8f..31204cc801 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryOptionsBuilder.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryOptionsBuilder.kt @@ -33,14 +33,14 @@ class QueryOptionsBuilder { if (request == null) { return queryOptions } - var queryPredicate: QueryPredicate? = QueryPredicateBuilder.fromSerializedMap( + val queryPredicate: QueryPredicate? = QueryPredicateBuilder.fromSerializedMap( request["queryPredicate"].safeCastToMap(), modelSchema ) - var querySortInput: List? = QuerySortBuilder.fromSerializedList( + val querySortInput: List? = QuerySortBuilder.fromSerializedList( request["querySort"].safeCastToList() ) - var queryPagination: QueryPaginationInput? = QueryPaginationBuilder.fromSerializedMap( + val queryPagination: QueryPaginationInput? = QueryPaginationBuilder.fromSerializedMap( request["queryPagination"].safeCastToMap() ) diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt index d755dde17f..fc460c86d5 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt @@ -117,7 +117,7 @@ class QueryPredicateBuilder { if (predicates.isNotEmpty()) { throw IllegalArgumentException( "More than one predicates added in the `not` queryPredicate operation." + - " Predicates Size: " + predicates.size + " Predicates Size: " + predicates.size ) } resultQueryPredicate = diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt index 94fc346bd7..351c6b6a96 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt @@ -59,8 +59,8 @@ import java.util.concurrent.CountDownLatch @RunWith(RobolectricTestRunner::class) class AmplifyDataStoreHubTest { - lateinit var flutterPlugin: AmplifyDataStorePlugin - lateinit var modelSchema: ModelSchema + private lateinit var flutterPlugin: AmplifyDataStorePlugin + private lateinit var modelSchema: ModelSchema private var mockDataStore = mock(DataStoreCategory::class.java) private var mockAmplifyDataStorePlugin = mock(AWSDataStorePlugin::class.java) private var mockAmplifyHub = mock(AWSHubPlugin::class.java) @@ -83,31 +83,32 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_outboxMutationEnqueued_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "outboxMutationEnqueuedEvent.json", - HashMap::class.java - ) as HashMap - ) - var element: HashMap = eventData["element"] as HashMap + val eventData: HashMap = ( + readMapFromFile( + "hub", + "outboxMutationEnqueuedEvent.json", + HashMap::class.java + ) as HashMap + ) + val element: HashMap = eventData["element"] as HashMap var metadataMap: HashMap - var modelMap: HashMap = element["model"] as HashMap - var serializedData: HashMap = modelMap["serializedData"] as HashMap - var modelMetadata = ModelMetadata(modelMap["id"] as String, null, null, null) - var modelData = mapOf( + val modelMap: HashMap = element["model"] as HashMap + val serializedData: HashMap = modelMap["serializedData"] as HashMap + val modelMetadata = ModelMetadata(modelMap["id"] as String, null, null, null) + val modelData = mapOf( "id" to serializedData["id"] as String, "title" to serializedData["title"] as String, "created" to Temporal.DateTime(serializedData["created"] as String) ) - var instance = SerializedModel.builder() + val instance = SerializedModel.builder() .serializedData(modelData) .modelSchema(modelSchema) .build() - var modelWithMetadata: ModelWithMetadata = ModelWithMetadata(instance, modelMetadata) - var outboxMutationEnqueued: OutboxMutationEvent<*> = OutboxMutationEvent.create(eventData["modelName"] as String, modelWithMetadata) - var event: HubEvent<*> = HubEvent.create("outboxMutationEnqueued", outboxMutationEnqueued) + val modelWithMetadata: ModelWithMetadata = ModelWithMetadata(instance, modelMetadata) + val outboxMutationEnqueued: OutboxMutationEvent<*> = + OutboxMutationEvent.create(eventData["modelName"] as String, modelWithMetadata) + val event: HubEvent<*> = HubEvent.create("outboxMutationEnqueued", outboxMutationEnqueued) val latch = CountDownLatch(1) @@ -131,31 +132,37 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_outboxMutationProcessed_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "outboxMutationProcessedEvent.json", - HashMap::class.java - ) as HashMap - ) - var element: HashMap = eventData["element"] as HashMap - var metadataMap: HashMap = element["syncMetadata"] as HashMap - var modelMap: HashMap = element["model"] as HashMap - var serializedData: HashMap = modelMap["serializedData"] as HashMap - var modelMetadata = ModelMetadata(metadataMap["id"] as String, metadataMap["_deleted"] as Boolean, metadataMap["_version"] as Int, time) - var modelData = mapOf( + val eventData: HashMap = ( + readMapFromFile( + "hub", + "outboxMutationProcessedEvent.json", + HashMap::class.java + ) as HashMap + ) + val element: HashMap = eventData["element"] as HashMap + val metadataMap: HashMap = element["syncMetadata"] as HashMap + val modelMap: HashMap = element["model"] as HashMap + val serializedData: HashMap = modelMap["serializedData"] as HashMap + val modelMetadata = ModelMetadata( + metadataMap["id"] as String, + metadataMap["_deleted"] as Boolean, + metadataMap["_version"] as Int, + time + ) + val modelData = mapOf( "id" to serializedData["id"] as String, "title" to serializedData["title"] as String, "created" to Temporal.DateTime(serializedData["created"] as String) ) - var instance = SerializedModel.builder() + val instance = SerializedModel.builder() .serializedData(modelData) .modelSchema(modelSchema) .build() - var modelWithMetadata: ModelWithMetadata = ModelWithMetadata(instance, modelMetadata) - var outboxMutationProcessed: OutboxMutationEvent<*> = OutboxMutationEvent.create(eventData["modelName"] as String, modelWithMetadata) - var event: HubEvent<*> = HubEvent.create("outboxMutationProcessed", outboxMutationProcessed) + val modelWithMetadata: ModelWithMetadata = ModelWithMetadata(instance, modelMetadata) + val outboxMutationProcessed: OutboxMutationEvent<*> = + OutboxMutationEvent.create(eventData["modelName"] as String, modelWithMetadata) + val event: HubEvent<*> = HubEvent.create("outboxMutationProcessed", outboxMutationProcessed) val latch = CountDownLatch(1) @@ -179,15 +186,15 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_ready_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "readyEvent.json", - HashMap::class.java - ) as HashMap - ) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "readyEvent.json", + HashMap::class.java + ) as HashMap + ) - var event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.READY) + val event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.READY) val latch = CountDownLatch(1) @@ -209,15 +216,15 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_subscriptionsEstablished_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "subscriptionsEstablishedEvent.json", - HashMap::class.java - ) as HashMap - ) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "subscriptionsEstablishedEvent.json", + HashMap::class.java + ) as HashMap + ) - var event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.SUBSCRIPTIONS_ESTABLISHED) + val event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.SUBSCRIPTIONS_ESTABLISHED) val latch = CountDownLatch(1) @@ -239,15 +246,15 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_syncQueriesReady_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "syncQueriesReadyEvent.json", - HashMap::class.java - ) as HashMap - ) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "syncQueriesReadyEvent.json", + HashMap::class.java + ) as HashMap + ) - var event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.SYNC_QUERIES_READY) + val event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.SYNC_QUERIES_READY) val latch = CountDownLatch(1) @@ -271,15 +278,15 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_networkStatus_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "networkStatusEvent.json", - HashMap::class.java - ) as HashMap - ) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "networkStatusEvent.json", + HashMap::class.java + ) as HashMap + ) - var networkStatusEvent: NetworkStatusEvent = NetworkStatusEvent(eventData["active"] as Boolean) + val networkStatusEvent: NetworkStatusEvent = NetworkStatusEvent(eventData["active"] as Boolean) val latch = CountDownLatch(1) @@ -302,15 +309,15 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_outboxStatus_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "outboxStatusEvent.json", - HashMap::class.java - ) as HashMap - ) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "outboxStatusEvent.json", + HashMap::class.java + ) as HashMap + ) - var outboxStatusEvent = OutboxStatusEvent(eventData["isEmpty"] as Boolean) + val outboxStatusEvent = OutboxStatusEvent(eventData["isEmpty"] as Boolean) val latch = CountDownLatch(1) @@ -333,16 +340,16 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_syncQueriesStarted_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "syncQueriesStartedEvent.json", - HashMap::class.java - ) as HashMap - ) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "syncQueriesStartedEvent.json", + HashMap::class.java + ) as HashMap + ) - var syncQueriesStartedEvent: SyncQueriesStartedEvent = SyncQueriesStartedEvent(arrayOf("Post")) - var event: HubEvent<*> = HubEvent.create("syncQueriesStarted", syncQueriesStartedEvent) + val syncQueriesStartedEvent: SyncQueriesStartedEvent = SyncQueriesStartedEvent(arrayOf("Post")) + val event: HubEvent<*> = HubEvent.create("syncQueriesStarted", syncQueriesStartedEvent) val latch = CountDownLatch(1) @@ -365,22 +372,22 @@ class AmplifyDataStoreHubTest { @Test fun test_hub_modelSynced_event() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "modelSyncedEvent.json", - HashMap::class.java - ) as HashMap - ) - - var modelSyncedEvent: ModelSyncedEvent = ModelSyncedEvent( + val eventData: HashMap = ( + readMapFromFile( + "hub", + "modelSyncedEvent.json", + HashMap::class.java + ) as HashMap + ) + + val modelSyncedEvent: ModelSyncedEvent = ModelSyncedEvent( eventData["model"] as String, eventData["isFullSync"] as Boolean, eventData["added"] as Int, eventData["updated"] as Int, eventData["deleted"] as Int ) - var event: HubEvent<*> = HubEvent.create("modelSynced", modelSyncedEvent) + val event: HubEvent<*> = HubEvent.create("modelSynced", modelSyncedEvent) val latch = CountDownLatch(1) @@ -408,15 +415,15 @@ class AmplifyDataStoreHubTest { @Test fun test_replay_events() { flutterPlugin = AmplifyDataStorePlugin(eventHandler = mockStreamHandler, hubEventHandler = mockHubHandler) - var eventData: HashMap = ( - readMapFromFile( - "hub", - "readyEvent.json", - HashMap::class.java - ) as HashMap - ) - - var event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.READY) + val eventData: HashMap = ( + readMapFromFile( + "hub", + "readyEvent.json", + HashMap::class.java + ) as HashMap + ) + + val event: HubEvent<*> = HubEvent.create(DataStoreChannelEventName.READY) val latch = CountDownLatch(1) diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt index 082f154e58..2bc3a56128 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt @@ -30,7 +30,6 @@ import com.amplifyframework.core.model.query.Page import com.amplifyframework.core.model.query.QueryOptions import com.amplifyframework.core.model.query.Where import com.amplifyframework.core.model.query.predicate.QueryField.field -import com.amplifyframework.core.model.query.predicate.QueryPredicate import com.amplifyframework.core.model.query.predicate.QueryPredicateOperation.not import com.amplifyframework.core.model.query.predicate.QueryPredicates import com.amplifyframework.core.model.temporal.Temporal @@ -48,6 +47,7 @@ import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyString import org.mockito.ArgumentMatchers.eq import org.mockito.Mockito.RETURNS_SELF +import org.mockito.Mockito.`when` import org.mockito.Mockito.doAnswer import org.mockito.Mockito.mock import org.mockito.Mockito.mockStatic @@ -55,7 +55,6 @@ import org.mockito.Mockito.never import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoInteractions -import org.mockito.Mockito.`when` import org.mockito.invocation.InvocationOnMock import org.robolectric.RobolectricTestRunner import java.lang.reflect.Field @@ -64,9 +63,9 @@ import java.util.concurrent.TimeUnit @RunWith(RobolectricTestRunner::class) class AmplifyDataStorePluginTest { - lateinit var flutterPlugin: AmplifyDataStorePlugin - lateinit var modelSchema: ModelSchema - lateinit var amplifySuccessResults: MutableList + private lateinit var flutterPlugin: AmplifyDataStorePlugin + private lateinit var modelSchema: ModelSchema + private lateinit var amplifySuccessResults: MutableList private var mockDataStore = mock(DataStoreCategory::class.java) private var mockAmplifyDataStorePlugin = mock(AWSDataStorePlugin::class.java) @@ -114,7 +113,7 @@ class AmplifyDataStorePluginTest { modelProvider.addCustomTypeSchema("Contact", contactSchema) modelSchema = flutterPlugin.modelProvider.modelSchemas()["Post"]!! - amplifySuccessResults = mutableListOf( + amplifySuccessResults = mutableListOf( SerializedModel.builder() .serializedData( mapOf( @@ -344,12 +343,12 @@ class AmplifyDataStorePluginTest { @Test fun test_query_api_error() { val testRequest: HashMap = ( - readMapFromFile( - "query_api", - "request/only_model_name.json", - HashMap::class.java - ) as HashMap - ) + readMapFromFile( + "query_api", + "request/only_model_name.json", + HashMap::class.java + ) as HashMap + ) doAnswer { invocation: InvocationOnMock -> assertEquals("Post", invocation.arguments[0]) @@ -398,12 +397,12 @@ class AmplifyDataStorePluginTest { @Test fun test_delete_success_result_no_predicates() { val testRequest: HashMap = ( - readMapFromFile( - "delete_api", - "request/instance_no_predicate.json", - HashMap::class.java - ) as HashMap - ) + readMapFromFile( + "delete_api", + "request/instance_no_predicate.json", + HashMap::class.java + ) as HashMap + ) val serializedModelData: HashMap = testRequest["serializedModel"] as HashMap @@ -425,10 +424,10 @@ class AmplifyDataStorePluginTest { (invocation.arguments[2] as Consumer>).accept( dataStoreItemChange ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin).delete( - any(), - any(), + any(), + any(), any>>(), any>() ) @@ -442,12 +441,12 @@ class AmplifyDataStorePluginTest { fun test_delete_api_error() { val testRequest: HashMap = ( - readMapFromFile( - "delete_api", - "request/instance_no_predicate.json", - HashMap::class.java - ) as HashMap - ) + readMapFromFile( + "delete_api", + "request/instance_no_predicate.json", + HashMap::class.java + ) as HashMap + ) val serializedModelData: HashMap = testRequest["serializedModel"] as HashMap @@ -462,10 +461,10 @@ class AmplifyDataStorePluginTest { (invocation.arguments[3] as Consumer).accept( dataStoreException ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin).delete( - any(), - any(), + any(), + any(), any>>(), any>() ) @@ -503,12 +502,12 @@ class AmplifyDataStorePluginTest { @Test fun test_save_success_result_no_predicates() { val testRequest: HashMap = ( - readMapFromFile( - "save_api", - "request/instance_without_predicate.json", - HashMap::class.java - ) as HashMap - ) + readMapFromFile( + "save_api", + "request/instance_without_predicate.json", + HashMap::class.java + ) as HashMap + ) val serializedModelData: HashMap = testRequest["serializedModel"] as HashMap @@ -531,10 +530,10 @@ class AmplifyDataStorePluginTest { (invocation.arguments[2] as Consumer>).accept( dataStoreItemChange ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin).save( - any(), - any(), + any(), + any(), any>>(), any>() ) @@ -548,12 +547,12 @@ class AmplifyDataStorePluginTest { fun test_save_api_error() { val testRequest: HashMap = ( - readMapFromFile( - "save_api", - "request/instance_without_predicate.json", - HashMap::class.java - ) as HashMap - ) + readMapFromFile( + "save_api", + "request/instance_without_predicate.json", + HashMap::class.java + ) as HashMap + ) val serializedModelData: HashMap = testRequest["serializedModel"] as HashMap @@ -569,10 +568,10 @@ class AmplifyDataStorePluginTest { (invocation.arguments[3] as Consumer).accept( dataStoreException ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin).save( - any(), - any(), + any(), + any(), any>>(), any>() ) @@ -623,7 +622,7 @@ class AmplifyDataStorePluginTest { any>(), any>>(), any>(), - any() + any() ) flutterPlugin.onSetUpObserve(mockResult) @@ -647,7 +646,7 @@ class AmplifyDataStorePluginTest { any>(), any>>(), any>(), - any() + any() ) flutterPlugin.onSetUpObserve(mockResult) @@ -662,12 +661,12 @@ class AmplifyDataStorePluginTest { hubEventHandler = mockHubHandler ) val eventData: HashMap = ( - readMapFromFile( - "observe_api", - "post_type_success_event.json", - HashMap::class.java - ) as HashMap - ) + readMapFromFile( + "observe_api", + "post_type_success_event.json", + HashMap::class.java + ) as HashMap + ) val modelData = mapOf( "id" to "43036c6b-8044-4309-bddc-262b6c686026", "title" to "Title 2", @@ -695,7 +694,7 @@ class AmplifyDataStorePluginTest { any>(), any>>(), any>(), - any() + any() ) flutterPlugin.onSetUpObserve(mockResult) @@ -719,7 +718,7 @@ class AmplifyDataStorePluginTest { any>(), any>>(), any>(), - any() + any() ) flutterPlugin.onSetUpObserve(mockResult) @@ -741,9 +740,9 @@ class AmplifyDataStorePluginTest { fun test_clear_success_result() { doAnswer { invocation: InvocationOnMock -> (invocation.arguments[0] as Action).call() - null as Void? + null }.`when`(mockAmplifyDataStorePlugin) - .clear(any(), any>()) + .clear(any(), any>()) flutterPlugin.onClear(mockResult) @@ -756,9 +755,9 @@ class AmplifyDataStorePluginTest { (invocation.arguments[1] as Consumer).accept( dataStoreException ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin) - .clear(any(), any>()) + .clear(any(), any>()) flutterPlugin.onClear(mockResult) @@ -876,9 +875,9 @@ class AmplifyDataStorePluginTest { fun test_onStart_success() { doAnswer { invocation: InvocationOnMock -> (invocation.arguments[0] as Action).call() - null as Void? + null }.`when`(mockAmplifyDataStorePlugin) - .start(any(), any>()) + .start(any(), any>()) flutterPlugin.onStart(mockResult) @@ -891,9 +890,9 @@ class AmplifyDataStorePluginTest { (invocation.arguments[1] as Consumer).accept( dataStoreException ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin) - .start(any(), any>()) + .start(any(), any>()) flutterPlugin.onStart(mockResult) @@ -911,9 +910,9 @@ class AmplifyDataStorePluginTest { fun test_onStop_success() { doAnswer { invocation: InvocationOnMock -> (invocation.arguments[0] as Action).call() - null as Void? + null }.`when`(mockAmplifyDataStorePlugin) - .stop(any(), any>()) + .stop(any(), any>()) flutterPlugin.onStop(mockResult) @@ -926,9 +925,9 @@ class AmplifyDataStorePluginTest { (invocation.arguments[1] as Consumer).accept( dataStoreException ) - null as Void? + null }.`when`(mockAmplifyDataStorePlugin) - .stop(any(), any>()) + .stop(any(), any>()) flutterPlugin.onStop(mockResult) diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt index d09ea09218..b0ac982acf 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt @@ -26,18 +26,18 @@ import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class AmplifyModelSchemaTest { - var schemasMap: Map = ( - readMapFromFile( - "model_schema", - "model_schema_maps.json", - HashMap::class.java - ) as HashMap - ) + private var schemasMap: Map = ( + readMapFromFile( + "model_schema", + "model_schema_maps.json", + HashMap::class.java + ) as HashMap + ) @Test fun test_schema_blog_with_hasMany() { - var inputMap = schemasMap["BlogSchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["BlogSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), @@ -47,8 +47,8 @@ class AmplifyModelSchemaTest { @Test fun test_schema_comment_with_belongsTo() { - var inputMap = schemasMap["CommentSchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["CommentSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), @@ -58,8 +58,8 @@ class AmplifyModelSchemaTest { @Test fun test_schema_post_with_datetime_int_hasMany_belongsTo() { - var inputMap = schemasMap["PostSchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["PostSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), @@ -70,8 +70,8 @@ class AmplifyModelSchemaTest { @Test fun test_schema_postAuthComplex_with_authRules() { // Generate Flutter ModelSchema from map input - var inputMap = schemasMap["PostAuthComplexSchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["PostAuthComplexSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), @@ -82,8 +82,8 @@ class AmplifyModelSchemaTest { @Test fun test_schema_postAuthComplex_with_authRules_with_provider_userpools() { // Generate Flutter ModelSchema from map input - var inputMap = schemasMap["PostAuthComplexWithProviderUserPoolsSchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["PostAuthComplexWithProviderUserPoolsSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), @@ -94,8 +94,8 @@ class AmplifyModelSchemaTest { @Test fun test_schema_postAuthComplex_with_authRules_with_provider_apikey() { // Generate Flutter ModelSchema from map input - var inputMap = schemasMap["PostAuthComplexWithProviderApiKeySchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["PostAuthComplexWithProviderApiKeySchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), @@ -106,8 +106,8 @@ class AmplifyModelSchemaTest { @Test fun test_schema_allTypeModel() { // Generate Flutter ModelSchema from map input - var inputMap = schemasMap["AllTypeModelSchema"] as Map - var modelSchema = FlutterModelSchema(inputMap) + val inputMap = schemasMap["AllTypeModelSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) // Verify result assertEquals( modelSchema.convertToNativeModelSchema(), diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifySerializedModelTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifySerializedModelTest.kt index ac9b246fe9..2458f2917e 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifySerializedModelTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifySerializedModelTest.kt @@ -24,18 +24,18 @@ import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class AmplifySerializedModelTest { - var serializedModelMaps: Map = ( - readMapFromFile( - "model_schema", - "serialized_model_maps.json", - HashMap::class.java - ) as HashMap - ) + private var serializedModelMaps: Map = ( + readMapFromFile( + "model_schema", + "serialized_model_maps.json", + HashMap::class.java + ) as HashMap + ) @Test fun test_schema_blog_with_hasMany() { - var flutterSerializedModel = FlutterSerializedModel(blogSerializedModel) - var refMap = serializedModelMaps["BlogSerializedMap"] as Map + val flutterSerializedModel = FlutterSerializedModel(blogSerializedModel) + val refMap = serializedModelMaps["BlogSerializedMap"] as Map // Verify result Assert.assertEquals( @@ -46,8 +46,8 @@ class AmplifySerializedModelTest { @Test fun test_schema_comment_with_hasMany() { - var flutterSerializedModel = FlutterSerializedModel(commentSerializedModel) - var refMap = serializedModelMaps["CommentSerializedMap"] as Map + val flutterSerializedModel = FlutterSerializedModel(commentSerializedModel) + val refMap = serializedModelMaps["CommentSerializedMap"] as Map // Verify result Assert.assertEquals( @@ -58,8 +58,8 @@ class AmplifySerializedModelTest { @Test fun test_schema_post_with_hasMany() { - var flutterSerializedModel = FlutterSerializedModel(postSerializedModel) - var refMap = serializedModelMaps["PostSerializedMap"] as Map + val flutterSerializedModel = FlutterSerializedModel(postSerializedModel) + val refMap = serializedModelMaps["PostSerializedMap"] as Map // Verify result Assert.assertEquals( diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/Latch.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/Latch.kt index 8b067b5c87..9d3f090bf9 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/Latch.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/Latch.kt @@ -32,9 +32,8 @@ object Latch { * @param waitTimeMs Time to wait before throwing an error * @throws RuntimeException If the latch doesn't count down in the allotted timeout */ - fun await(latch: CountDownLatch, waitTimeMs: Long) { - val didCountDown: Boolean - didCountDown = try { + private fun await(latch: CountDownLatch, waitTimeMs: Long) { + val didCountDown: Boolean = try { latch.await(waitTimeMs, TimeUnit.MILLISECONDS) } catch (interruptedException: InterruptedException) { throw RuntimeException("Thread interrupted while wait for latch count down.", interruptedException) diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt index 67d097b5b0..1ad243afd1 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt @@ -32,102 +32,102 @@ val postSchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "title" to - ModelField.builder() - .name("title") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("title") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "created" to - ModelField.builder() - .name("created") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .build(), + ModelField.builder() + .name("created") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .build(), "rating" to - ModelField.builder() - .name("rating") - .javaClassForValue(Integer::class.java) - .targetType("Integer") - .isRequired(false) - .isArray(false) - .build(), + ModelField.builder() + .name("rating") + .javaClassForValue(Integer::class.java) + .targetType("Integer") + .isRequired(false) + .isArray(false) + .build(), "blog" to - ModelField.builder() - .name("blog") - .javaClassForValue(Model::class.java) - .targetType("Blog") - .isRequired(false) - .isArray(false) - .isModel(true) - .build(), + ModelField.builder() + .name("blog") + .javaClassForValue(Model::class.java) + .targetType("Blog") + .isRequired(false) + .isArray(false) + .isModel(true) + .build(), "comments" to - ModelField.builder() - .name("comments") - .javaClassForValue(List::class.java) - .targetType("Comment") - .isRequired(false) - .isArray(true) - .build(), + ModelField.builder() + .name("comments") + .javaClassForValue(List::class.java) + .targetType("Comment") + .isRequired(false) + .isArray(true) + .build(), "likeCount" to - ModelField.builder() - .name("likeCount") - .javaClassForValue(Integer::class.java) - .targetType("Integer") - .isRequired(false) - .isArray(false) - .build(), + ModelField.builder() + .name("likeCount") + .javaClassForValue(Integer::class.java) + .targetType("Integer") + .isRequired(false) + .isArray(false) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .associations( mapOf( "blog" to - ModelAssociation.builder() - .name("BelongsTo") - .targetName("blogID") - .build(), + ModelAssociation.builder() + .name("BelongsTo") + .targetName("blogID") + .build(), "comments" to - ModelAssociation.builder() - .name("HasMany") - .associatedName("post") - .associatedType("Post") - .build() + ModelAssociation.builder() + .name("HasMany") + .associatedName("post") + .associatedType("Post") + .build() ) ) @@ -140,49 +140,49 @@ val postAuthComplexSchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "title" to - ModelField.builder() - .name("title") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("title") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "owner" to - ModelField.builder() - .name("owner") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(false) - .isArray(false) - .build(), + ModelField.builder() + .name("owner") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(false) + .isArray(false) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .authRules( @@ -191,16 +191,16 @@ val postAuthComplexSchema = ModelSchema.builder() .authStrategy(AuthStrategy.OWNER) .ownerField("owner") .identityClaim("cognito:username") - /* - .operations( - listOf( - ModelOperation.READ, - ModelOperation.DELETE, - ModelOperation.UPDATE, - ModelOperation.CREATE - ) - ) - */ + /* + .operations( + listOf( + ModelOperation.READ, + ModelOperation.DELETE, + ModelOperation.UPDATE, + ModelOperation.CREATE + ) + ) + */ .build() ) ) @@ -213,40 +213,40 @@ val postAuthComplexWithProviderUserPoolsSchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "owner" to - ModelField.builder() - .name("owner") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(false) - .isArray(false) - .build(), + ModelField.builder() + .name("owner") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(false) + .isArray(false) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .authRules( @@ -268,32 +268,32 @@ val postAuthComplexWithProviderApiKeySchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .authRules( @@ -313,58 +313,58 @@ val commentSchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "post" to - ModelField.builder() - .name("post") - .javaClassForValue(Model::class.java) - .targetType("Post") - .isRequired(false) - .isArray(false) - .isModel(true) - .build(), + ModelField.builder() + .name("post") + .javaClassForValue(Model::class.java) + .targetType("Post") + .isRequired(false) + .isArray(false) + .isModel(true) + .build(), "content" to - ModelField.builder() - .name("content") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("content") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .associations( mapOf( "post" to - ModelAssociation.builder() - .name("BelongsTo") - .targetName("postID") - .build() + ModelAssociation.builder() + .name("BelongsTo") + .targetName("postID") + .build() ) ) .modelClass(SerializedModel::class.java) @@ -376,58 +376,58 @@ val blogSchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "name" to - ModelField.builder() - .name("name") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("name") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "posts" to - ModelField.builder() - .name("posts") - .javaClassForValue(List::class.java) - .targetType("Post") - .isRequired(false) - .isArray(true) - .build(), + ModelField.builder() + .name("posts") + .javaClassForValue(List::class.java) + .targetType("Post") + .isRequired(false) + .isArray(true) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .associations( mapOf( "posts" to - ModelAssociation.builder() - .name("HasMany") - .associatedName("blog") - .associatedType("Blog") - .build() + ModelAssociation.builder() + .name("HasMany") + .associatedName("blog") + .associatedType("Blog") + .build() ) ) .modelClass(SerializedModel::class.java) @@ -439,104 +439,104 @@ val allTypeModelSchema = ModelSchema.builder() .fields( mapOf( "id" to - ModelField.builder() - .name("id") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "stringType" to - ModelField.builder() - .name("stringType") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("stringType") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "intType" to - ModelField.builder() - .name("intType") - .javaClassForValue(Integer::class.java) - .targetType("Integer") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("intType") + .javaClassForValue(Integer::class.java) + .targetType("Integer") + .isRequired(true) + .isArray(false) + .build(), "floatType" to - ModelField.builder() - .name("floatType") - .javaClassForValue(Double::class.javaObjectType) - .targetType("Double") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("floatType") + .javaClassForValue(Double::class.javaObjectType) + .targetType("Double") + .isRequired(true) + .isArray(false) + .build(), "boolType" to - ModelField.builder() - .name("boolType") - .javaClassForValue(Boolean::class.javaObjectType) - .targetType("Boolean") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("boolType") + .javaClassForValue(Boolean::class.javaObjectType) + .targetType("Boolean") + .isRequired(true) + .isArray(false) + .build(), "dateType" to - ModelField.builder() - .name("dateType") - .javaClassForValue(Temporal.Date::class.java) - .targetType("AWSDate") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("dateType") + .javaClassForValue(Temporal.Date::class.java) + .targetType("AWSDate") + .isRequired(true) + .isArray(false) + .build(), "dateTimeType" to - ModelField.builder() - .name("dateTimeType") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("dateTimeType") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(true) + .isArray(false) + .build(), "timeType" to - ModelField.builder() - .name("timeType") - .javaClassForValue(Temporal.Time::class.java) - .targetType("AWSTime") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("timeType") + .javaClassForValue(Temporal.Time::class.java) + .targetType("AWSTime") + .isRequired(true) + .isArray(false) + .build(), "timestampType" to - ModelField.builder() - .name("timestampType") - .javaClassForValue(Temporal.Timestamp::class.java) - .targetType("AWSTimestamp") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("timestampType") + .javaClassForValue(Temporal.Timestamp::class.java) + .targetType("AWSTimestamp") + .isRequired(true) + .isArray(false) + .build(), "enumType" to - ModelField.builder() - .name("enumType") - .javaClassForValue(String::class.java) - .targetType("String") - .isRequired(true) - .isArray(false) - .build(), + ModelField.builder() + .name("enumType") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), "createdAt" to - ModelField.builder() - .name("createdAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build(), + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), "updatedAt" to - ModelField.builder() - .name("updatedAt") - .javaClassForValue(Temporal.DateTime::class.java) - .targetType("AWSDateTime") - .isRequired(false) - .isArray(false) - .isReadOnly(true) - .build() + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() ) ) .modelClass(SerializedModel::class.java) diff --git a/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift index f2524dbbf9..be3ddbc478 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import Amplify @testable import amplify_datastore class AmplifyModelSchemaUnitTests: XCTestCase { - let modelSchemaMap: [String: Any] = try! readJsonMap(filePath: "model_schema_maps") let customTypeSchemaMap: [String: Any] = try! readJsonMap(filePath: "custom_type_schema_maps") let customTypeSchemasRegistry = FlutterSchemaRegistry() @@ -29,7 +28,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { // This also tests the deserialization functionality for CustomType schemas ["AddressSchema", "PhoneSchema", "ContactSchema", "CustomBSchema", "CustomASchema"].forEach { schemaName in do { - let serializedCustomType = customTypeSchemaMap[schemaName] as! [String : Any] + let serializedCustomType = customTypeSchemaMap[schemaName] as! [String: Any] customTypeSchemasRegistry.addModelSchema( modelName: serializedCustomType["name"] as! String, modelSchema: try FlutterModelSchema( @@ -44,7 +43,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_blog_with_hasMany() throws { let flutterBlogSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["BlogSchema"] as! [String : Any] ) + serializedData: modelSchemaMap["BlogSchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.BlogSchema, flutterBlogSchema) @@ -52,7 +51,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_comment_with_belongsTo() throws { let flutterBlogSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["CommentSchema"] as! [String : Any] ) + serializedData: modelSchemaMap["CommentSchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.CommentSchema, flutterBlogSchema) @@ -60,7 +59,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_post_with_datetime_int_hasMany_belongsTo() throws{ let flutterBlogSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["PostSchema"] as! [String : Any] ) + serializedData: modelSchemaMap["PostSchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.PostSchema, flutterBlogSchema) @@ -68,7 +67,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_postAuthComplex_with_authRules() throws{ let postAuthComplexSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["PostAuthComplexSchema"] as! [String : Any] ) + serializedData: modelSchemaMap["PostAuthComplexSchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.PostAuthComplexSchema, postAuthComplexSchema) @@ -76,7 +75,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_postAuthComplex_with_authRules_provider_userpools() throws{ let postAuthComplexSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["PostAuthComplexWithProviderUserPoolsSchema"] as! [String : Any] ) + serializedData: modelSchemaMap["PostAuthComplexWithProviderUserPoolsSchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.PostAuthComplexWithProviderUserPoolsSchema, postAuthComplexSchema) @@ -84,7 +83,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_postAuthComplex_with_authRules_provider_apikey() throws{ let postAuthComplexSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["PostAuthComplexWithProviderApiKeySchema"] as! [String : Any] ) + serializedData: modelSchemaMap["PostAuthComplexWithProviderApiKeySchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.PostAuthComplexWithProviderApiKeySchema, postAuthComplexSchema) @@ -92,7 +91,7 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_schema_allTypeModel() throws{ let allTypeModelSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["AllTypeModelSchema"] as! [String : Any] ) + serializedData: modelSchemaMap["AllTypeModelSchema"] as! [String: Any] ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) XCTAssertEqual(SchemaData.AllTypeModelSchema, allTypeModelSchema) diff --git a/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift index 2f0e8b6fc4..d6bb4e7ffc 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -13,14 +13,12 @@ * permissions and limitations under the License. */ - import XCTest import Amplify @testable import AmplifyPlugins @testable import amplify_datastore class AmplifySerializedModelUnitTests: XCTestCase { - let serializedModelMaps: [String: Any] = try! readJsonMap(filePath: "serialized_model_maps") let modelSchemaRegistry = SchemaData.modelSchemaRegistry let customTypeSchemasRegistry = SchemaData.customTypeSchemaRegistry @@ -31,63 +29,63 @@ class AmplifySerializedModelUnitTests: XCTestCase { customTypeSchemaRegistry: customTypeSchemasRegistry, modelName: SchemaData.BlogSchema.name ) - let refMap = serializedModelMaps["BlogSerializedMap"] as! [String : Any] - - XCTAssertEqual(ourMap["id"] as! String , refMap["id"] as! String) - XCTAssertEqual(ourMap["modelName"] as! String , refMap["modelName"] as! String) - - let ourSd : [String: Any] = ourMap["serializedData"] as! [String: Any] - let refSd : [String: Any] = refMap["serializedData"] as! [String: Any] - - XCTAssertEqual(ourSd["id"] as! String , refSd["id"] as! String) - XCTAssertEqual(ourSd["name"] as! String , refSd["name"] as! String) + let refMap = serializedModelMaps["BlogSerializedMap"] as! [String: Any] + + XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) + XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) + + let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] + let refSd: [String: Any] = refMap["serializedData"] as! [String: Any] + + XCTAssertEqual(ourSd["id"] as! String, refSd["id"] as! String) + XCTAssertEqual(ourSd["name"] as! String, refSd["name"] as! String) } - + func test_comment_belongs_serialization() throws { let ourMap = try FlutterSerializedModelData.CommentSerializedModel.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemasRegistry, modelName: SchemaData.CommentSchema.name ) - let refMap = serializedModelMaps["CommentSerializedMap"] as! [String : Any] - - XCTAssertEqual(ourMap["id"] as! String , refMap["id"] as! String) - XCTAssertEqual(ourMap["modelName"] as! String , refMap["modelName"] as! String) - - let ourSd : [String: Any] = ourMap["serializedData"] as! [String: Any] - let refSd : [String: Any] = refMap["serializedData"] as! [String: Any] - - XCTAssertEqual(ourSd["id"] as! String , refSd["id"] as! String) - XCTAssertEqual(ourSd["content"] as! String , refSd["content"] as! String) - - let ourNs : [String: Any] = ourSd["post"] as! [String: Any] - let refNs : [String: Any] = refSd["post"] as! [String: Any] - - XCTAssertEqual(ourNs["id"] as! String , refNs["id"] as! String) + let refMap = serializedModelMaps["CommentSerializedMap"] as! [String: Any] + + XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) + XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) + + let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] + let refSd: [String: Any] = refMap["serializedData"] as! [String: Any] + + XCTAssertEqual(ourSd["id"] as! String, refSd["id"] as! String) + XCTAssertEqual(ourSd["content"] as! String, refSd["content"] as! String) + + let ourNs: [String: Any] = ourSd["post"] as! [String: Any] + let refNs: [String: Any] = refSd["post"] as! [String: Any] + + XCTAssertEqual(ourNs["id"] as! String, refNs["id"] as! String) } - + func test_post_with_datetime_int_hasMany_serialization() throws { let ourMap = try FlutterSerializedModelData.PostSerializedModel.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemasRegistry, modelName: SchemaData.PostSchema.name ) - let refMap = serializedModelMaps["PostSerializedMap"] as! [String : Any] - - XCTAssertEqual(ourMap["id"] as! String , refMap["id"] as! String) - XCTAssertEqual(ourMap["modelName"] as! String , refMap["modelName"] as! String) - - let ourSd : [String: Any] = ourMap["serializedData"] as! [String: Any] - let refSd : [String: Any] = refMap["serializedData"] as! [String: Any] - - XCTAssertEqual(ourSd["id"] as! String , refSd["id"] as! String) - XCTAssertEqual(ourSd["title"] as! String , refSd["title"] as! String) - XCTAssertEqual(ourSd["created"] as! String , refSd["created"] as! String) - - let ourNs : [String: Any] = ourSd["blog"] as! [String: Any] - let refNs : [String: Any] = refSd["blog"] as! [String: Any] - - XCTAssertEqual(ourNs["id"] as! String , refNs["id"] as! String) + let refMap = serializedModelMaps["PostSerializedMap"] as! [String: Any] + + XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) + XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) + + let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] + let refSd: [String: Any] = refMap["serializedData"] as! [String: Any] + + XCTAssertEqual(ourSd["id"] as! String, refSd["id"] as! String) + XCTAssertEqual(ourSd["title"] as! String, refSd["title"] as! String) + XCTAssertEqual(ourSd["created"] as! String, refSd["created"] as! String) + + let ourNs: [String: Any] = ourSd["blog"] as! [String: Any] + let refNs: [String: Any] = refSd["blog"] as! [String: Any] + + XCTAssertEqual(ourNs["id"] as! String, refNs["id"] as! String) } func test_post_with_nested_models_serialization() throws { @@ -96,7 +94,7 @@ class AmplifySerializedModelUnitTests: XCTestCase { customTypeSchemaRegistry: customTypeSchemasRegistry, modelName: SchemaData.PostSchema.name) )["serializedData"] as! [String: Any] - let expectedData = (serializedModelMaps["PostSerializedMap"] as! [String : Any])["serializedData"] as! [String: Any] + let expectedData = (serializedModelMaps["PostSerializedMap"] as! [String: Any])["serializedData"] as! [String: Any] let serializedBlog = (serializedData["blog"] as! [String: Any])["serializedData"] as! [String: String] let expectedBlog = (expectedData["blog"] as! [String: Any])["serializedData"] as! [String: String] @@ -110,34 +108,33 @@ class AmplifySerializedModelUnitTests: XCTestCase { let serializedDepartment = (serializedAuthor["department"] as! [String: Any])["serializedData"] as! [String: String] let expectedDepartment = (expectedAuthor["department"] as! [String: Any])["serializedData"] as! [String: String] - + XCTAssertEqual(serializedDepartment, expectedDepartment) } - - + func test_allTypeModel_serialization() throws { let ourMap = try FlutterSerializedModelData.AllTypeModelSerializedModel.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemasRegistry, modelName: SchemaData.AllTypeModelSchema.name ) - let refMap = serializedModelMaps["AllTypeModelSerializedMap"] as! [String : Any] - - XCTAssertEqual(ourMap["id"] as! String , refMap["id"] as! String) - XCTAssertEqual(ourMap["modelName"] as! String , refMap["modelName"] as! String) - - let ourSd : [String: Any] = ourMap["serializedData"] as! [String: Any] - let refSd : [String: Any] = refMap["serializedData"] as! [String: Any] - - XCTAssertEqual(ourSd["id"] as! String , refSd["id"] as! String) - XCTAssertEqual(ourSd["stringType"] as! String , refSd["stringType"] as! String) - XCTAssertEqual(ourSd["intType"] as! NSNumber , refSd["intType"] as! NSNumber) - XCTAssertEqual(ourSd["floatType"] as! NSNumber , refSd["floatType"] as! NSNumber) - XCTAssertEqual(ourSd["boolType"] as! Bool , refSd["boolType"] as! Bool) - XCTAssertEqual(ourSd["dateType"] as! String , refSd["dateType"] as! String) - XCTAssertEqual(ourSd["dateTimeType"] as! String , refSd["dateTimeType"] as! String) - XCTAssertEqual(ourSd["timeType"] as! String , refSd["timeType"] as! String) - XCTAssertEqual(ourSd["enumType"] as! String , refSd["enumType"] as! String) + let refMap = serializedModelMaps["AllTypeModelSerializedMap"] as! [String: Any] + + XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) + XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) + + let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] + let refSd: [String: Any] = refMap["serializedData"] as! [String: Any] + + XCTAssertEqual(ourSd["id"] as! String, refSd["id"] as! String) + XCTAssertEqual(ourSd["stringType"] as! String, refSd["stringType"] as! String) + XCTAssertEqual(ourSd["intType"] as! NSNumber, refSd["intType"] as! NSNumber) + XCTAssertEqual(ourSd["floatType"] as! NSNumber, refSd["floatType"] as! NSNumber) + XCTAssertEqual(ourSd["boolType"] as! Bool, refSd["boolType"] as! Bool) + XCTAssertEqual(ourSd["dateType"] as! String, refSd["dateType"] as! String) + XCTAssertEqual(ourSd["dateTimeType"] as! String, refSd["dateTimeType"] as! String) + XCTAssertEqual(ourSd["timeType"] as! String, refSd["timeType"] as! String) + XCTAssertEqual(ourSd["enumType"] as! String, refSd["enumType"] as! String) } func test_model_registy_decoder_decodes_object() throws { @@ -146,7 +143,7 @@ class AmplifySerializedModelUnitTests: XCTestCase { let testModelContent = "a comment" let jsonString = "{\"id\":\"\(testModelId)\",\"content\":\"\(testModelContent)\"}" let decodedModel = try ModelRegistry.decode(modelName: modelName, from: jsonString) - XCTAssertEqual(decodedModel.id, testModelId); + XCTAssertEqual(decodedModel.id, testModelId) let values = (decodedModel as! FlutterSerializedModel).values XCTAssertEqual(values["content"], JSONValue.string(testModelContent)) } @@ -157,7 +154,7 @@ class AmplifySerializedModelUnitTests: XCTestCase { let testModelContent = "a comment" let jsonString = "[{\"id\":\"\(testModelId)\",\"content\":\"\(testModelContent)\"}]" let decodedModel = try ModelRegistry.decode(modelName: modelName, from: jsonString) - XCTAssertEqual(decodedModel.id, testModelId); + XCTAssertEqual(decodedModel.id, testModelId) let values = (decodedModel as! FlutterSerializedModel).values XCTAssertEqual(values["content"], JSONValue.string(testModelContent)) } @@ -181,17 +178,17 @@ class AmplifySerializedModelUnitTests: XCTestCase { ) let expected = serializedModelMaps["PersonModelSerializedMap"] as! [String: Any] - XCTAssertEqual(expected["id"] as! String , actual["id"] as! String) - XCTAssertEqual(expected["modelName"] as! String , actual["modelName"] as! String) + XCTAssertEqual(expected["id"] as! String, actual["id"] as! String) + XCTAssertEqual(expected["modelName"] as! String, actual["modelName"] as! String) let actualSerializedData = actual["serializedData"] as! [String: Any] let expectedSerializedData = actual["serializedData"] as! [String: Any] - XCTAssertEqual(expectedSerializedData["id"] as! String , actualSerializedData["id"] as! String) - XCTAssertEqual(expectedSerializedData["name"] as! String , actualSerializedData["name"] as! String) + XCTAssertEqual(expectedSerializedData["id"] as! String, actualSerializedData["id"] as! String) + XCTAssertEqual(expectedSerializedData["name"] as! String, actualSerializedData["name"] as! String) let actualContact = actualSerializedData["contact"] as! [String: Any] let expectedContact = expectedSerializedData["contact"] as! [String: Any] - XCTAssertEqual(expectedContact["customTypeName"] as! String, actualContact["customTypeName"] as! String); + XCTAssertEqual(expectedContact["customTypeName"] as! String, actualContact["customTypeName"] as! String) let actualContactSerializedData = actualContact["serializedData"] as! [String: Any] let expectedContactSerializedData = expectedContact["serializedData"] as! [String: Any] @@ -225,7 +222,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { XCTAssertEqual(expectedElementSerializedData["postalCode"], actualElementSerializedData["postalCode"]) } - let actualAddresses = actualSerializedData["propertiesAddresses"] as! [[String: Any]] let expectedAddresses = expectedSerializedData["propertiesAddresses"] as! [[String: Any]] diff --git a/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift b/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift index d27ffbc3d2..1fec05d9c0 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -23,8 +23,7 @@ import Combine let testHubSchema: ModelSchema = ModelSchema.init(name: "Post") class DataStoreHubEventStreamHandlerTests: XCTestCase { - - var pluginUnderTest: SwiftAmplifyDataStorePlugin = SwiftAmplifyDataStorePlugin() + var pluginUnderTest: SwiftAmplifyDataStorePlugin = .init() var modelSchemaRegistry = FlutterSchemaRegistry() var customTypeSchemaRegistry = FlutterSchemaRegistry() @@ -32,7 +31,7 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { modelSchemaRegistry.addModelSchema(modelName: "Post", modelSchema: testSchema) modelSchemaRegistry.registerModels(registry: ModelRegistry.self) } - + func test_hub_modelSyncedEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -40,7 +39,8 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "modelSynced") XCTAssertEqual(flutterEvent["model"] as! String, "Blog") XCTAssertEqual(flutterEvent["added"] as! Int, 1) @@ -56,10 +56,10 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { modelSyncedEventBuilder = ModelSyncedEvent.Builder() modelSyncedEventBuilder.modelName = "Blog" modelSyncedEventBuilder.added = 1 - modelSyncedEventBuilder.deleted = 0; - modelSyncedEventBuilder.updated = 0; - modelSyncedEventBuilder.isDeltaSync = false; - modelSyncedEventBuilder.isFullSync = true; + modelSyncedEventBuilder.deleted = 0 + modelSyncedEventBuilder.updated = 0 + modelSyncedEventBuilder.isDeltaSync = false + modelSyncedEventBuilder.isFullSync = true let hubHandler = MockDataStoreHubHandler() // passing the expectation we are awaiting into the enclosed class @@ -76,7 +76,7 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { // prevent collisions between tests hubHandler.onCancel(withArguments: nil) } - + func test_hub_readyEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -84,7 +84,8 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "ready") innerExpect?.fulfill() } @@ -94,14 +95,13 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { hubHandler.setExpectation(outerExpect: expect) hubHandler.registerModelsForHub(modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry) hubHandler.setHubListener() - + let readyEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.ready) Amplify.Hub.dispatch(to: .dataStore, payload: readyEventPayload) waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) - } - + func test_hub_subscriptionEstablishedEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -109,7 +109,8 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "subscriptionEstablished") innerExpect?.fulfill() } @@ -133,7 +134,8 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "syncQueriesReady") innerExpect?.fulfill() } @@ -143,13 +145,13 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { hubHandler.setExpectation(outerExpect: expect) hubHandler.registerModelsForHub(modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry) hubHandler.setHubListener() - + let syncQueriesReadyPayload = HubPayload(eventName: HubPayload.EventName.DataStore.syncQueriesReady) Amplify.Hub.dispatch(to: .dataStore, payload: syncQueriesReadyPayload) waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) } - + func test_hub_networkStatusEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -157,26 +159,27 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "networkStatus") XCTAssertEqual(flutterEvent["active"] as? Bool, true) innerExpect?.fulfill() } } - + let networkStatusEvent = NetworkStatusEvent(active: true) let hubHandler = MockDataStoreHubHandler() hubHandler.setExpectation(outerExpect: expect) hubHandler.registerModelsForHub(modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry) hubHandler.setHubListener() - + let networkStatusPayload = HubPayload(eventName: HubPayload.EventName.DataStore.networkStatus, data: networkStatusEvent) Amplify.Hub.dispatch(to: .dataStore, payload: networkStatusPayload) waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) } - + func test_hub_outboxStatusEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -184,26 +187,27 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "outboxStatus") XCTAssertEqual(flutterEvent["isEmpty"] as? Bool, true) innerExpect?.fulfill() } } - + let outboxStatusEvent = OutboxStatusEvent(isEmpty: true) let hubHandler = MockDataStoreHubHandler() hubHandler.setExpectation(outerExpect: expect) hubHandler.registerModelsForHub(modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry) hubHandler.setHubListener() - + let outboxStatusPayload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxStatus, data: outboxStatusEvent) Amplify.Hub.dispatch(to: .dataStore, payload: outboxStatusPayload) waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) } - + func test_hub_syncQueriesStartedEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -211,25 +215,26 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { + + override func sendEvent(flutterEvent: [String: Any]) { XCTAssertEqual(flutterEvent["eventName"] as! String, "syncQueriesStarted") XCTAssertEqual(flutterEvent["models"] as! String, "[\"Blog\"]") innerExpect?.fulfill() } } - + let syncQueriesStartedEvent = SyncQueriesStartedEvent(models: ["Blog"]) let hubHandler = MockDataStoreHubHandler() hubHandler.setExpectation(outerExpect: expect) hubHandler.registerModelsForHub(modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry) hubHandler.setHubListener() - + let syncQueriesStartedPayload = HubPayload(eventName: HubPayload.EventName.DataStore.syncQueriesStarted, data: syncQueriesStartedEvent) Amplify.Hub.dispatch(to: .dataStore, payload: syncQueriesStartedPayload) waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) } - + func test_hub_outboxMutationEnqueued_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -237,11 +242,12 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { - let element = flutterEvent["element"] as! [String : Any] - let model = element["model"] as! [String : Any] - let syncMetaData = element["syncMetadata"] as! [String : Any] - let serializedData = model["serializedData"] as! [String : Any] + + override func sendEvent(flutterEvent: [String: Any]) { + let element = flutterEvent["element"] as! [String: Any] + let model = element["model"] as! [String: Any] + let syncMetaData = element["syncMetadata"] as! [String: Any] + let serializedData = model["serializedData"] as! [String: Any] XCTAssertEqual(flutterEvent["eventName"] as! String, "outboxMutationEnqueued") XCTAssertEqual(flutterEvent["modelName"] as! String, "Post") XCTAssertEqual(syncMetaData["_lastChangedAt"] as? Int, nil) @@ -252,27 +258,27 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { innerExpect?.fulfill() } } - - let uuid = UUID().uuidString + + let uuid = UUID().uuidString let modelMap = [ "model": "Post", "id": uuid, "title": "Title 1" ] - + let serializedModel = FlutterSerializedModel(id: uuid, map: try FlutterDataStoreRequestUtils.getJSONValue(modelMap)) let outboxMutationEnqueuedEvent = OutboxMutationEvent.fromModelWithoutMetadata(modelName: "Post", model: serializedModel) let hubHandler = MockDataStoreHubHandler() hubHandler.setExpectation(outerExpect: expect) hubHandler.registerModelsForHub(modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry) hubHandler.setHubListener() - + let outboxMutationEnqueuedPayload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxMutationEnqueued, data: outboxMutationEnqueuedEvent) Amplify.Hub.dispatch(to: .dataStore, payload: outboxMutationEnqueuedPayload) waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) } - + func test_hub_outboxMutationProcessedEvent_success() throws { let expect = expectation(description: "listener was invoked") class MockDataStoreHubHandler: DataStoreHubEventStreamHandler { @@ -280,11 +286,12 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { func setExpectation(outerExpect: XCTestExpectation) { innerExpect = outerExpect } - override func sendEvent(flutterEvent: [String : Any]) { - let element = flutterEvent["element"] as! [String : Any] - let model = element["model"] as! [String : Any] - let serializedData = model["serializedData"] as! [String : Any] - let syncMetaData = element["syncMetadata"] as! [String : Any] + + override func sendEvent(flutterEvent: [String: Any]) { + let element = flutterEvent["element"] as! [String: Any] + let model = element["model"] as! [String: Any] + let serializedData = model["serializedData"] as! [String: Any] + let syncMetaData = element["syncMetadata"] as! [String: Any] XCTAssertEqual(flutterEvent["eventName"] as! String, "outboxMutationProcessed") XCTAssertEqual(flutterEvent["modelName"] as! String, "Post") XCTAssertEqual(syncMetaData["_lastChangedAt"] as? Int, 123) @@ -296,23 +303,23 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { innerExpect?.fulfill() } } - - let uuid = UUID().uuidString + + let uuid = UUID().uuidString let modelMap = [ "modelName": "Post", "id": uuid, "title": "Title 1" ] - + let serializedModel = FlutterSerializedModel(id: uuid, map: try FlutterDataStoreRequestUtils.getJSONValue(modelMap)) - + let syncMetadata = MutationSyncMetadata(id: uuid, deleted: false, lastChangedAt: 123, version: 1) - + let hubHandler = MockDataStoreHubHandler() - + do { let anyModel = try serializedModel.eraseToAnyModel() let mutationSync = MutationSync(model: anyModel, syncMetadata: syncMetadata) @@ -329,12 +336,12 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { waitForExpectations(timeout: 1.0) hubHandler.onCancel(withArguments: nil) } - + func test_hot_restart_replays_sync_and_ready_events() { let payloads = [ HubPayload( - eventName: HubPayload.EventName.DataStore.ready, - context: nil, + eventName: HubPayload.EventName.DataStore.ready, + context: nil, data: nil ), HubPayload( @@ -350,13 +357,14 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { ) ), ] - + var events: Set = [] func buildEventSink(expectCount: Int) -> (FlutterEventSink, XCTestExpectation) { let expect = expectation(description: "Emits \(expectCount) events") let eventSink = { (event: Any?) in guard let eventMap = event as? [String: Any], - let eventName = eventMap["eventName"] as? String else { + let eventName = eventMap["eventName"] as? String + else { XCTFail("Bad event: \(event ?? "nil")") return } @@ -367,34 +375,34 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { } return (eventSink, expect) } - + let hubHandler = DataStoreHubEventStreamHandler() var (eventSink, expect) = buildEventSink(expectCount: payloads.count) let listenError = hubHandler.onListen(withArguments: nil, eventSink: eventSink) XCTAssertNil(listenError) - + for payload in payloads { Amplify.Hub.dispatch(to: .dataStore, payload: payload) } - + let expectedEvents = Set(payloads.map { shortEventName(eventName: $0.eventName) }) - + wait(for: [expect], timeout: 1) XCTAssertEqual(events, expectedEvents) - + (eventSink, expect) = buildEventSink(expectCount: payloads.count) func hotRestart() { events = [] - + let cancelError = hubHandler.onCancel(withArguments: nil) XCTAssertNil(cancelError) - + let listenError = hubHandler.onListen(withArguments: nil, eventSink: eventSink) XCTAssertNil(listenError) } - + hotRestart() - + wait(for: [expect], timeout: 1) XCTAssertEqual(events, expectedEvents) } diff --git a/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift index 6584d1cc38..d815ab1de0 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -22,10 +22,10 @@ import amplify_core let testSchema: ModelSchema = ModelSchema.init(name: "Post") let amplifySuccessResults: [FlutterSerializedModel] = - (try! readJsonArray(filePath: "2_results") as! [[String: Any]]).map { (serializedModel) in + (try! readJsonArray(filePath: "2_results") as! [[String: Any]]).map { serializedModel in FlutterSerializedModel.init( id: serializedModel["id"] as! String, - map: try! getJSONValue(serializedModel["serializedData"] as! [String : Any])) + map: try! getJSONValue(serializedModel["serializedData"] as! [String: Any])) } let id: QueryField = field("id") @@ -35,8 +35,7 @@ let created: QueryField = field("created") var eventSentExp: XCTestExpectation? class DataStorePluginUnitTests: XCTestCase { - - var pluginUnderTest: SwiftAmplifyDataStorePlugin = SwiftAmplifyDataStorePlugin() + var pluginUnderTest: SwiftAmplifyDataStorePlugin = .init() var modelSchemaRegistry = FlutterSchemaRegistry() var customTypeSchemaRegistry = FlutterSchemaRegistry() @@ -46,14 +45,14 @@ class DataStorePluginUnitTests: XCTestCase { } func test_query_success_result_with_query_parameters() throws { - class MockDataStoreBridge: DataStoreBridge { override func onQuery(_ modelType: M.Type, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, sort sortInput: [QuerySortDescriptor]? = nil, paginate paginationInput: QueryPaginationInput? = nil, - completion: DataStoreCallback<[M]>) throws { + completion: DataStoreCallback<[M]>) throws + { // Validations that we called the native library correctly XCTAssert(FlutterSerializedModel.self == modelType) XCTAssertEqual(testSchema.name, modelSchema.name) @@ -76,11 +75,11 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onQuery( args: try readJsonMap(filePath: "model_name_with_all_query_parameters") as [String: Any], - flutterResult: { (results) -> Void in + flutterResult: { results in if let results = results as? [[String: Any]] { // Result #1 (Any/AnyObject is not equatable so we iterate over fields we know) XCTAssertEqual("4281dfba-96c8-4a38-9a8e-35c7e893ea47", results[0]["id"] as! String) @@ -102,14 +101,14 @@ class DataStorePluginUnitTests: XCTestCase { } func test_query_called_with_no_query_parameters_failed_with_invalid_condition() throws { - class MockDataStoreBridge: DataStoreBridge { override func onQuery(_ modelType: M.Type, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, sort sortInput: [QuerySortDescriptor]? = nil, paginate paginationInput: QueryPaginationInput? = nil, - completion: DataStoreCallback<[M]>) throws { + completion: DataStoreCallback<[M]>) throws + { // Validations that we called the native library correctly (i.e. valid defaults in this case) XCTAssert(FlutterSerializedModel.self == modelType) XCTAssertEqual(testSchema.name, modelSchema.name) @@ -122,16 +121,16 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onQuery( args: try readJsonMap(filePath: "only_model_name") as [String: Any], - flutterResult: { (results) -> Void in + flutterResult: { results in if let exception = results as? FlutterError { // Result #1 (Any/AnyObject is not equatable so we iterate over fields we know) XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("test error", errorMap["message"] as? String) XCTAssertEqual("test recovery suggestion", errorMap["recoverySuggestion"] as? String) } else { @@ -141,7 +140,6 @@ class DataStorePluginUnitTests: XCTestCase { } func test_delete_success_result() throws { - class MockDataStoreBridge: DataStoreBridge { override func onDelete( serializedModel: FlutterSerializedModel, @@ -156,26 +154,26 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onDelete( args: try readJsonMap(filePath: "instance_no_predicate") as [String: Any], - flutterResult: { (results) in - if (results == nil) { + flutterResult: { results in + if results == nil { print("success") } }) } func test_delete_failed_with_invalid_internal_operation() throws { - class MockDataStoreBridge: DataStoreBridge { override func onDelete( serializedModel: FlutterSerializedModel, modelSchema: ModelSchema, where: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { // Validations that we called the native library correctly XCTAssertEqual(testSchema.name, modelSchema.name) // Return from the mock @@ -183,16 +181,16 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onDelete( args: try readJsonMap(filePath: "instance_no_predicate") as [String: Any], - flutterResult: { (results) -> Void in + flutterResult: { results in if let exception = results as? FlutterError { XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("test error", errorMap["message"] as? String) XCTAssertEqual("test recovery suggestion", errorMap["recoverySuggestion"] as? String) } else { @@ -202,7 +200,6 @@ class DataStorePluginUnitTests: XCTestCase { } func test_observe_success_event() throws { - eventSentExp = expectation(description: "event was sent") class MockDataStoreBridge: DataStoreBridge { @@ -213,7 +210,7 @@ class DataStorePluginUnitTests: XCTestCase { } class MockStreamHandler: DataStoreObserveEventStreamHandler { - override func sendEvent(flutterEvent: [String : Any]) { + override func sendEvent(flutterEvent: [String: Any]) { eventSentExp?.fulfill() XCTAssertEqual("create", flutterEvent["eventType"] as! String) @@ -226,8 +223,8 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() - let streamHandler: MockStreamHandler = MockStreamHandler() + let dataStoreBridge = MockDataStoreBridge() + let streamHandler = MockStreamHandler() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry, dataStoreObserveEventStreamHandler: streamHandler) @@ -249,7 +246,6 @@ class DataStorePluginUnitTests: XCTestCase { } func test_observe_received_bad_event() throws { - class MockDataStoreBridge: DataStoreBridge { let mockPublisher = PassthroughSubject() override func onObserve() throws -> AnyPublisher { @@ -258,16 +254,17 @@ class DataStorePluginUnitTests: XCTestCase { } class MockStreamHandler: DataStoreObserveEventStreamHandler { - override func sendEvent(flutterEvent: [String : Any]) { + override func sendEvent(flutterEvent: [String: Any]) { XCTFail() } + override func sendError(flutterError: FlutterError) { XCTFail() } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() - let streamHandler: MockStreamHandler = MockStreamHandler() + let dataStoreBridge = MockDataStoreBridge() + let streamHandler = MockStreamHandler() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry, dataStoreObserveEventStreamHandler: streamHandler) @@ -280,11 +277,9 @@ class DataStorePluginUnitTests: XCTestCase { modelName: "Post", json: "unparsable json", mutationType: MutationEvent.MutationType.create)) - } func test_observe_error_event() throws { - eventSentExp = expectation(description: "error was sent") class MockDataStoreBridge: DataStoreBridge { @@ -299,14 +294,14 @@ class DataStorePluginUnitTests: XCTestCase { eventSentExp?.fulfill() XCTAssertEqual("DataStoreException", flutterError.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, flutterError.message) - let errorMap: [String: Any] = flutterError.details as! [String : Any] + let errorMap: [String: Any] = flutterError.details as! [String: Any] XCTAssertEqual("This is test error", errorMap["message"] as? String) XCTAssertEqual("And a test recovery suggestion", errorMap["recoverySuggestion"] as? String) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() - let streamHandler: MockStreamHandler = MockStreamHandler() + let dataStoreBridge = MockDataStoreBridge() + let streamHandler = MockStreamHandler() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry, dataStoreObserveEventStreamHandler: streamHandler) @@ -333,8 +328,8 @@ class DataStorePluginUnitTests: XCTestCase { class MockStreamHandler: DataStoreObserveEventStreamHandler {} - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() - let streamHandler: MockStreamHandler = MockStreamHandler() + let dataStoreBridge = MockDataStoreBridge() + let streamHandler = MockStreamHandler() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry, dataStoreObserveEventStreamHandler: streamHandler) @@ -344,42 +339,42 @@ class DataStorePluginUnitTests: XCTestCase { } func test_clear_success() throws { - class MockDataStoreBridge: DataStoreBridge { override func onClear( - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { // Return from the mock completion(.emptyResult) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onClear( - flutterResult: {(result) in + flutterResult: {result in XCTAssertNil(result) }) } func test_clear_failure_with_unknown_error() throws { - class MockDataStoreBridge: DataStoreBridge { override func onClear( - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { // Return from the mock completion(.failure(causedBy: DataStoreError.unknown("test error", "test recovery suggestion", nil))) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onClear( - flutterResult: { (result) -> Void in + flutterResult: { result in if let exception = result as? FlutterError { XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("test error", errorMap["message"] as? String) XCTAssertEqual("test recovery suggestion", errorMap["recoverySuggestion"] as? String) } else { @@ -391,15 +386,16 @@ class DataStorePluginUnitTests: XCTestCase { func test_start_success() throws { class MockDataStoreBridge: DataStoreBridge { override func onStart( - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { completion(.successfulVoid) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onStart( - flutterResult: {(result) in + flutterResult: {result in XCTAssertNil(result) }) } @@ -407,19 +403,20 @@ class DataStorePluginUnitTests: XCTestCase { func test_start_error() throws { class MockDataStoreBridge: DataStoreBridge { override func onStart( - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { completion(.failure(causedBy: DataStoreError.unknown("test error", "test recovery suggestion", nil))) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onStart( - flutterResult: { (result) -> Void in + flutterResult: { result in if let exception = result as? FlutterError { XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("test error", errorMap["message"] as? String) XCTAssertEqual("test recovery suggestion", errorMap["recoverySuggestion"] as? String) } else { @@ -431,15 +428,16 @@ class DataStorePluginUnitTests: XCTestCase { func test_stop_success() throws { class MockDataStoreBridge: DataStoreBridge { override func onStop( - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { completion(.successfulVoid) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onStop( - flutterResult: {(result) in + flutterResult: {result in XCTAssertNil(result) }) } @@ -447,19 +445,20 @@ class DataStorePluginUnitTests: XCTestCase { func test_stop_error() throws { class MockDataStoreBridge: DataStoreBridge { override func onStop( - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { completion(.failure(causedBy: DataStoreError.unknown("test error", "test recovery suggestion", nil))) } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onStop( - flutterResult: { (result) -> Void in + flutterResult: { result in if let exception = result as? FlutterError { XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("test error", errorMap["message"] as? String) XCTAssertEqual("test recovery suggestion", errorMap["recoverySuggestion"] as? String) } else { @@ -476,7 +475,8 @@ class DataStorePluginUnitTests: XCTestCase { serializedModel: M, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { // Validations that we called the native library correctly XCTAssertEqual("9fc5fab4-37ff-4566-97e5-19c5d58a4c22", serializedModel.id) XCTAssertEqual(testSchema.name, modelSchema.name) @@ -486,12 +486,12 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onSave( args: testArgs, - flutterResult: { (result) in + flutterResult: { result in XCTAssertNil(result) }) } @@ -504,7 +504,8 @@ class DataStorePluginUnitTests: XCTestCase { serializedModel: M, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { // Validations that we called the native library correctly XCTAssertEqual("9fc5fab4-37ff-4566-97e5-19c5d58a4c22", serializedModel.id) XCTAssertEqual(testSchema.name, modelSchema.name) @@ -514,16 +515,16 @@ class DataStorePluginUnitTests: XCTestCase { } } - let dataStoreBridge: MockDataStoreBridge = MockDataStoreBridge() + let dataStoreBridge = MockDataStoreBridge() pluginUnderTest = SwiftAmplifyDataStorePlugin(bridge: dataStoreBridge, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onSave( args: testArgs, - flutterResult: { (results) -> Void in + flutterResult: { results in if let exception = results as? FlutterError { XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("test error", errorMap["message"] as? String) XCTAssertEqual("test recovery suggestion", errorMap["recoverySuggestion"] as? String) } else { @@ -533,17 +534,16 @@ class DataStorePluginUnitTests: XCTestCase { } func test_save_with_malformed_error() throws { - pluginUnderTest = SwiftAmplifyDataStorePlugin( bridge: DataStoreBridge(), modelSchemaRegistry: modelSchemaRegistry, customTypeSchemasRegistry: customTypeSchemaRegistry) pluginUnderTest.onSave( args: [:], - flutterResult: { (results) -> Void in + flutterResult: { results in if let exception = results as? FlutterError { XCTAssertEqual("DataStoreException", exception.code) XCTAssertEqual(ErrorMessages.defaultFallbackErrorMessage, exception.message) - let errorMap: [String: Any] = exception.details as! [String : Any] + let errorMap: [String: Any] = exception.details as! [String: Any] XCTAssertEqual("The modelName was not passed in the arguments", errorMap["message"] as? String) XCTAssertEqual("The request should include the modelName of type String", errorMap["recoverySuggestion"] as? String) } else { diff --git a/packages/amplify_datastore/example/ios/unit_tests/GetJsonFromFileUtil.swift b/packages/amplify_datastore/example/ios/unit_tests/GetJsonFromFileUtil.swift index 7dfbcaffad..1484fc03fa 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/GetJsonFromFileUtil.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/GetJsonFromFileUtil.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/packages/amplify_datastore/example/ios/unit_tests/ModelSchemaEquatableExtensions.swift b/packages/amplify_datastore/example/ios/unit_tests/ModelSchemaEquatableExtensions.swift index dcc7918bfd..530f445b45 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/ModelSchemaEquatableExtensions.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/ModelSchemaEquatableExtensions.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ import Foundation import Amplify -extension ModelSchema : Equatable { +extension ModelSchema: Equatable { public static func == (lhs: ModelSchema, rhs: ModelSchema) -> Bool { return lhs.name == rhs.name && @@ -26,7 +26,7 @@ extension ModelSchema : Equatable { } } -extension AuthRule : Equatable { +extension AuthRule: Equatable { public static func == (lhs: AuthRule, rhs: AuthRule) -> Bool { return lhs.allow == rhs.allow && @@ -39,16 +39,17 @@ extension AuthRule : Equatable { } } -extension ModelOperation : Comparable { +extension ModelOperation: Comparable { public static func < (lhs: ModelOperation, rhs: ModelOperation) -> Bool { return String(describing: lhs) < String(describing: rhs) } + public static func == (lhs: ModelOperation, rhs: ModelOperation) -> Bool { return String(describing: lhs) < String(describing: rhs) } } -extension ModelField : Equatable { +extension ModelField: Equatable { public static func == (lhs: ModelField, rhs: ModelField) -> Bool { return lhs.name == rhs.name && @@ -56,9 +57,9 @@ extension ModelField : Equatable { } } -extension ModelFieldType : Equatable { +extension ModelFieldType: Equatable { public static func == (lhs: ModelFieldType, rhs: ModelFieldType) -> Bool { - switch(lhs, rhs) { + switch (lhs, rhs) { case (.string, .string): return true case (.int, .int): @@ -98,6 +99,6 @@ extension ModelFieldType : Equatable { extension Array where Element: Comparable { func containsSameElements(as other: [Element]) -> Bool { - return self.count == other.count && self.sorted() == other.sorted() + return count == other.count && sorted() == other.sorted() } } diff --git a/packages/amplify_datastore/example/ios/unit_tests/QueryPaginationUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/QueryPaginationUnitTests.swift index 802de2d6dc..0c7184666d 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/QueryPaginationUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/QueryPaginationUnitTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,36 +18,35 @@ import Amplify import AmplifyPlugins @testable import amplify_datastore -extension QueryPaginationInput : Equatable { +extension QueryPaginationInput: Equatable { public static func == (lhs: QueryPaginationInput, rhs: QueryPaginationInput) -> Bool { return lhs.page == rhs.page && lhs.limit == rhs.limit } } class QueryPaginationBuilderUnitTests: XCTestCase { - let customPageAndLimit = ["page": 3, "limit": 200] as [String: Any] let firstPage = ["page": 0, "limit": 100] as [String: Any] let firstResult = ["page": 0, "limit": 1] as [String: Any] - + func test_when_requesting_custom_page_and_limit() throws { - let expected : QueryPaginationInput = QueryPaginationInput.page(3, limit: 200) + let expected = QueryPaginationInput.page(3, limit: 200) let actual = QueryPaginationBuilder.fromSerializedMap(customPageAndLimit) XCTAssertEqual(expected, actual) } - + func test_when_requesting_first_page() throws { - let expected : QueryPaginationInput = QueryPaginationInput.firstPage + let expected = QueryPaginationInput.firstPage let actual = QueryPaginationBuilder.fromSerializedMap(firstPage) XCTAssertEqual(expected, actual) } - + func test_when_requesting_first_result() throws { - let expected : QueryPaginationInput = QueryPaginationInput.firstResult + let expected = QueryPaginationInput.firstResult let actual = QueryPaginationBuilder.fromSerializedMap(firstResult) XCTAssertEqual(expected, actual) } - + func test_when_no_input_given_results_in_no_pagination() throws { let actual = QueryPaginationBuilder.fromSerializedMap(nil) XCTAssertNil(actual) diff --git a/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift index 177f68d35b..86efa864a9 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,33 +18,32 @@ import Amplify @testable import amplify_datastore class QueryPredicateBuilderUnitTests: XCTestCase { - private let id: QueryField = field("id") private let title: QueryField = field("title") private let rating: QueryField = field("rating") private let created: QueryField = field("created") - + func test_when_id_not_equals() throws { XCTAssertEqual( id.ne("123"), try QueryPredicateBuilder.fromSerializedMap(readJsonMap(filePath: "id_not_equals")) as! QueryPredicateOperation ) } - + func test_when_rating_greater_or_equal() throws { XCTAssertEqual( rating.ge(4), try QueryPredicateBuilder.fromSerializedMap( readJsonMap(filePath: "rating_greater_or_equal")) as! QueryPredicateOperation) } - + func test_complex_nested_and_or() throws { XCTAssertEqual( rating.le(4).and(id.contains("abc").or(title.beginsWith("def"))), try QueryPredicateBuilder.fromSerializedMap( readJsonMap(filePath: "complex_nested")) as! QueryPredicateGroup) } - + func test_when_group_with_only_and() throws { XCTAssertEqual( rating.between(start: 1, end: 4) @@ -54,7 +53,7 @@ class QueryPredicateBuilderUnitTests: XCTestCase { try QueryPredicateBuilder.fromSerializedMap( readJsonMap(filePath: "group_with_only_and")) as! QueryPredicateGroup) } - + func test_when_mixed_and_or() throws { XCTAssertEqual( rating.lt(4).and(id.contains("abc")).or(title.contains("def")), @@ -62,14 +61,14 @@ class QueryPredicateBuilderUnitTests: XCTestCase { readJsonMap(filePath: "group_mixed_and_or")) as! QueryPredicateGroup) } - + func test_when_rating_gt_but_not_eq() throws { XCTAssertEqual( rating.gt(4).and(not(rating.eq(1))), try QueryPredicateBuilder.fromSerializedMap( readJsonMap(filePath: "mixed_with_not")) as! QueryPredicateGroup) } - + func test_when_negate_complex_predicate() throws { XCTAssertEqual( not( @@ -77,14 +76,14 @@ class QueryPredicateBuilderUnitTests: XCTestCase { try QueryPredicateBuilder.fromSerializedMap( readJsonMap(filePath: "negate_complex_predicate")) as! QueryPredicateGroup) } - + func test_when_operands_are_bool_and_double() throws { XCTAssertEqual( rating.eq(1.3).and(created.eq(1)), // TODO FIXME: bool are represented as integers in Json deserialization try QueryPredicateBuilder.fromSerializedMap( readJsonMap(filePath: "bool_and_double_operands")) as! QueryPredicateGroup) } - + func test_when_no_input_given_results_in_all_predicate() throws { XCTAssertEqual( QueryPredicateConstant.all, diff --git a/packages/amplify_datastore/example/ios/unit_tests/QuerySortBuilderUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/QuerySortBuilderUnitTests.swift index d9c39ce1bb..74468d283d 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/QuerySortBuilderUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/QuerySortBuilderUnitTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -20,34 +20,33 @@ import Amplify // Extending for simple assertions on the objects equality. // Also imported AmplifyPlugins as testable to get access to internal fields -extension QuerySortDescriptor : Equatable { +extension QuerySortDescriptor: Equatable { public static func == (lhs: QuerySortDescriptor, rhs: QuerySortDescriptor) -> Bool { return lhs.fieldName == rhs.fieldName && lhs.order.rawValue == rhs.order.rawValue } } class QuerySortBuilderUnitTests: XCTestCase { - let sortByIdAsc = [["field": "id", "order": "ascending"]] as [[String: Any]] let multipleSorting = [["field": "id", "order": "ascending"], ["field": "rating", "order": "descending"]] as [[String: Any]] let badSortingInput = [["field": "id", "order": "chaos"]] as [[String: Any]] let badInputFormat = [["field": "id", "order": 4]] as [[String: Any]] - + func test_when_sorting_by_id_ascending() throws { - let expected : QuerySortDescriptor = QuerySortDescriptor.init(fieldName: "id", order: .ascending) + let expected = QuerySortDescriptor.init(fieldName: "id", order: .ascending) let actual = try QuerySortBuilder.fromSerializedList(sortByIdAsc)?[0] XCTAssertEqual(expected, actual) } - + func test_when_sorting_by_id_ascending_and_rating_descending() throws { - let expected : [QuerySortDescriptor] = [ + let expected: [QuerySortDescriptor] = [ QuerySortDescriptor.init(fieldName: "id", order: .ascending), QuerySortDescriptor.init(fieldName: "rating", order: .descending) ] let actual = try QuerySortBuilder.fromSerializedList(multipleSorting) XCTAssertEqual(expected, actual) } - + func test_when_bad_input_given() throws { XCTAssertThrowsError( try QuerySortBuilder.fromSerializedList(badSortingInput)) { error in @@ -55,7 +54,7 @@ class QuerySortBuilderUnitTests: XCTestCase { XCTAssertEqual((error as! DataStoreError).recoverySuggestion, "Please create an issue to amplify-flutter repo.") } } - + func test_when_null_or_empty_input_given() throws { XCTAssertEqual(nil, try QuerySortBuilder.fromSerializedList(nil)) XCTAssertEqual(nil, try QuerySortBuilder.fromSerializedList([])) diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift b/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift index 5c7f84ae05..0c411efe5e 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,28 +18,27 @@ import Amplify @testable import amplify_datastore struct FlutterSerializedModelData { - - static var BlogSerializedModel : FlutterSerializedModel = - FlutterSerializedModel(id: "999", map: [ - "id" : JSONValue.string("999"), - "name" : JSONValue.string("blog name"), - ]); - static var CommentSerializedModel : FlutterSerializedModel = - FlutterSerializedModel(id: "999", map: [ - "id" : JSONValue.string("999"), - "post" : JSONValue.object([ - "id" : "555" + static var BlogSerializedModel: FlutterSerializedModel = + .init(id: "999", map: [ + "id": JSONValue.string("999"), + "name": JSONValue.string("blog name"), + ]) + static var CommentSerializedModel: FlutterSerializedModel = + .init(id: "999", map: [ + "id": JSONValue.string("999"), + "post": JSONValue.object([ + "id": "555" ]), - "content" : "content" - ]); + "content": "content" + ]) - static var PostSerializedModel : FlutterSerializedModel = - FlutterSerializedModel(id: "999", map: [ - "id" : JSONValue.string("999"), - "title" : JSONValue.string("post title"), - "created" : JSONValue.string("2020-11-25T01:28:49.000Z"), - "blog" : JSONValue.object([ - "id" : "555", + static var PostSerializedModel: FlutterSerializedModel = + .init(id: "999", map: [ + "id": JSONValue.string("999"), + "title": JSONValue.string("post title"), + "created": JSONValue.string("2020-11-25T01:28:49.000Z"), + "blog": JSONValue.object([ + "id": "555", "name": "Blog 1" ]), "author": JSONValue.object([ @@ -51,24 +50,24 @@ struct FlutterSerializedModelData { "description": "Testing department 1" ]) ]) - ]); + ]) - static var AllTypeModelSerializedModel : FlutterSerializedModel = - FlutterSerializedModel(id: "999", map: [ - "id" : JSONValue.string("999"), - "stringType" : JSONValue.string("string value"), + static var AllTypeModelSerializedModel: FlutterSerializedModel = + .init(id: "999", map: [ + "id": JSONValue.string("999"), + "stringType": JSONValue.string("string value"), "intType": JSONValue.number(10), - "floatType" : JSONValue.number(9.99), - "boolType" : JSONValue.boolean(true), - "dateType" : JSONValue.string("2020-09-09Z"), - "dateTimeType" : JSONValue.string("2020-11-25T01:28:49.000Z"), - "timeType" : JSONValue.string("20:20:20:020Z"), - "timestampType" : JSONValue.number(999), - "enumType" : JSONValue.string("maybe") - ]); + "floatType": JSONValue.number(9.99), + "boolType": JSONValue.boolean(true), + "dateType": JSONValue.string("2020-09-09Z"), + "dateTimeType": JSONValue.string("2020-11-25T01:28:49.000Z"), + "timeType": JSONValue.string("20:20:20:020Z"), + "timestampType": JSONValue.number(999), + "enumType": JSONValue.string("maybe") + ]) static var PersonModelSerializedModel: FlutterSerializedModel = - FlutterSerializedModel( + .init( id: "123", map: [ "id": JSONValue.string("123"), diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift b/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift index 80b02a0463..059e7a214d 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,8 +18,7 @@ import Amplify @testable import amplify_datastore struct SchemaData { - - static var PostSchema: ModelSchema = ModelSchema( + static var PostSchema: ModelSchema = .init( name: "Post", pluralName: "Posts", fields: [ @@ -34,8 +33,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var CommentSchema: ModelSchema = ModelSchema( + + static var CommentSchema: ModelSchema = .init( name: "Comment", pluralName: "Comments", fields: [ @@ -46,9 +45,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - - static var BlogSchema: ModelSchema = ModelSchema( + + static var BlogSchema: ModelSchema = .init( name: "Blog", pluralName: "Blogs", fields: [ @@ -59,8 +57,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var PostAuthComplexSchema: ModelSchema = ModelSchema( + + static var PostAuthComplexSchema: ModelSchema = .init( name: "PostAuthComplex", pluralName: "PostAuthComplexes", authRules: [ @@ -81,8 +79,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var PostAuthComplexWithProviderUserPoolsSchema: ModelSchema = ModelSchema( + + static var PostAuthComplexWithProviderUserPoolsSchema: ModelSchema = .init( name: "PostAuthComplexWithProviderUserPools", pluralName: "PostAuthComplexWithProviderUserPools", authRules: [ @@ -103,8 +101,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var PostAuthComplexWithProviderApiKeySchema: ModelSchema = ModelSchema( + + static var PostAuthComplexWithProviderApiKeySchema: ModelSchema = .init( name: "PostAuthComplexWithProviderApiKey", pluralName: "PostAuthComplexWithProviderApiKeys", authRules: [ @@ -122,8 +120,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var AllTypeModelSchema: ModelSchema = ModelSchema( + + static var AllTypeModelSchema: ModelSchema = .init( name: "AllTypeModel", pluralName: "AllTypeModels", fields: [ @@ -141,8 +139,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var AuthorModelSchema: ModelSchema = ModelSchema( + + static var AuthorModelSchema: ModelSchema = .init( name: "Author", pluralName: "Authors", fields: [ @@ -153,8 +151,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var DepartmentSchema: ModelSchema = ModelSchema( + + static var DepartmentSchema: ModelSchema = .init( name: "Department", pluralName: "Departments", fields: [ @@ -165,8 +163,8 @@ struct SchemaData { "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), ] ) - - static var AddressSchema: ModelSchema = ModelSchema( + + static var AddressSchema: ModelSchema = .init( name: "Address", pluralName: "Addresses", fields: [ @@ -177,8 +175,8 @@ struct SchemaData { "postalCode": ModelField(name: "postalCode", type: .string, isRequired: true, isArray: false), ] ) - - static var PhoneSchema: ModelSchema = ModelSchema( + + static var PhoneSchema: ModelSchema = .init( name: "Phone", pluralName: "Phones", fields: [ @@ -187,8 +185,8 @@ struct SchemaData { "number": ModelField(name: "number", type: .string, isRequired: true, isArray: false), ] ) - - static var ContactSchema: ModelSchema = ModelSchema( + + static var ContactSchema: ModelSchema = .init( name: "Contact", pluralName: "Contacts", fields: [ @@ -201,16 +199,16 @@ struct SchemaData { ), ] ) - - static var CustomBSchema: ModelSchema = ModelSchema( + + static var CustomBSchema: ModelSchema = .init( name: "CustomB", pluralName: "CustomBs", fields: [ "field": ModelField(name: "field", type: .string, isRequired: true, isArray: false), ] ) - - static var CustomASchema: ModelSchema = ModelSchema( + + static var CustomASchema: ModelSchema = .init( name: "CustomA", pluralName: "CustomAs", fields: [ @@ -218,8 +216,8 @@ struct SchemaData { "field2": ModelField(name: "field2", type: .embedded(type: JSONValue.self, schema: SchemaData.CustomBSchema), isRequired: true), ] ) - - static var PersonSchema: ModelSchema = ModelSchema( + + static var PersonSchema: ModelSchema = .init( name: "Person", pluralName: "People", fields: [ @@ -234,7 +232,7 @@ struct SchemaData { "anotherCustomTypeTree": ModelField(name: "anotherCustomTypeTree", type: .embedded(type: JSONValue.self, schema: SchemaData.CustomASchema)), ] ) - + static var modelSchemas: [String: ModelSchema] { return [ PostSchema.name: PostSchema, @@ -247,7 +245,7 @@ struct SchemaData { PersonSchema.name: PersonSchema ] } - + static var customTypeSchemas: [String: ModelSchema] { return [ AddressSchema.name: AddressSchema, @@ -257,26 +255,26 @@ struct SchemaData { CustomASchema.name: CustomASchema ] } - + static var modelSchemaRegistry: FlutterSchemaRegistry { let modelSchemaRegistry = FlutterSchemaRegistry() - + for (key, value) in SchemaData.modelSchemas { modelSchemaRegistry.addModelSchema(modelName: key, modelSchema: value) } - + modelSchemaRegistry.registerModels(registry: ModelRegistry.self) - + return modelSchemaRegistry } - + static var customTypeSchemaRegistry: FlutterSchemaRegistry { let customTypeSchemaRegistry = FlutterSchemaRegistry() - + for (key, customTypeSchema) in SchemaData.customTypeSchemas { customTypeSchemaRegistry.addModelSchema(modelName: key, modelSchema: customTypeSchema) } - + return customTypeSchemaRegistry } } diff --git a/packages/amplify_datastore/ios/Classes/DataStoreBridge.swift b/packages/amplify_datastore/ios/Classes/DataStoreBridge.swift index cb1004cdb8..0552ff11df 100644 --- a/packages/amplify_datastore/ios/Classes/DataStoreBridge.swift +++ b/packages/amplify_datastore/ios/Classes/DataStoreBridge.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,42 +19,41 @@ import AmplifyPlugins import Combine public class DataStoreBridge { - func getPlugin() throws -> AWSDataStorePlugin { return try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin } - + func onQuery(_ modelType: M.Type, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, sort sortInput: [QuerySortDescriptor]? = nil, paginate paginationInput: QueryPaginationInput? = nil, - completion: DataStoreCallback<[M]>) throws { + completion: DataStoreCallback<[M]>) throws + { try getPlugin().query(modelType, modelSchema: modelSchema, where: predicate, sort: sortInput, paginate: paginationInput, completion: completion) - } func onSave(serializedModel: M, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) throws { + completion: @escaping DataStoreCallback) throws + { try getPlugin().save(serializedModel, modelSchema: modelSchema, where: predicate, completion: completion) - } func onDelete(serializedModel: FlutterSerializedModel, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) throws { - + completion: @escaping DataStoreCallback) throws + { try getPlugin().delete(serializedModel, modelSchema: modelSchema, where: predicate, diff --git a/packages/amplify_datastore/ios/Classes/DataStoreHubEventStreamHandler.swift b/packages/amplify_datastore/ios/Classes/DataStoreHubEventStreamHandler.swift index 61e545d1a2..85bea77fb3 100644 --- a/packages/amplify_datastore/ios/Classes/DataStoreHubEventStreamHandler.swift +++ b/packages/amplify_datastore/ios/Classes/DataStoreHubEventStreamHandler.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,18 +18,17 @@ import Amplify import AmplifyPlugins public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { - private var eventSink: FlutterEventSink? private var token: UnsubscribeToken? private var modelSchemaRegistry: FlutterSchemaRegistry? private var customTypeSchemaRegistry: FlutterSchemaRegistry? - + /// Protects `eventHistory` from mutual access. private let eventGuard = NSRecursiveLock() - + /// DataStore hub event history. Used to track events which may be lost on hot restart, such as sync and ready events. private var eventHistory: [HubPayload] = [] - + /// Event types which should be replayed on hot restart. private let replayableEvents: Set = [ HubPayload.EventName.DataStore.networkStatus, @@ -39,14 +38,14 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { HubPayload.EventName.DataStore.syncQueriesReady, HubPayload.EventName.DataStore.modelSynced, ] - + public func registerModelsForHub(modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry) { self.modelSchemaRegistry = modelSchemaRegistry self.customTypeSchemaRegistry = customTypeSchemaRegistry } public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.eventSink = events + eventSink = events setHubListener() return nil } @@ -54,17 +53,17 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { func ensureSchemaRegistries() throws -> ( modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry ) { - guard let modelSchemaRegistry = self.modelSchemaRegistry else { + guard let modelSchemaRegistry = modelSchemaRegistry else { throw FlutterDataStoreError.acquireSchemaForHub } - guard let customTypeSchemaRegistry = self.customTypeSchemaRegistry else { + guard let customTypeSchemaRegistry = customTypeSchemaRegistry else { throw FlutterDataStoreError.acquireSchemaForHub } return (modelSchemaRegistry, customTypeSchemaRegistry) } - + func setHubListener() { // Replay events. On hot restart, `onListen` is called again with a new listener. However, // DataStore will not re-emit events such as ready and modelSynced. As a result, this info @@ -78,7 +77,7 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { } } #endif - token = Amplify.Hub.listen(to: .dataStore) { [unowned self] (payload) in + token = Amplify.Hub.listen(to: .dataStore) { [unowned self] payload in #if DEBUG eventGuard.lock() defer { eventGuard.unlock() } @@ -89,65 +88,65 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { sendPayload(payload) } } - + func sendPayload(_ payload: HubPayload) { var flutterEvent: [String: Any]? switch payload.eventName { - case HubPayload.EventName.DataStore.networkStatus : + case HubPayload.EventName.DataStore.networkStatus: do { - let networkStatus = try FlutterNetworkStatusEvent (payload: payload) + let networkStatus = try FlutterNetworkStatusEvent(payload: payload) flutterEvent = networkStatus.toValueMap() } catch { print("Failed to parse and send networkStatus event: \(error)") } - case HubPayload.EventName.DataStore.outboxStatus : + case HubPayload.EventName.DataStore.outboxStatus: do { - let outboxStatus = try FlutterOutboxStatusEvent (payload: payload) + let outboxStatus = try FlutterOutboxStatusEvent(payload: payload) flutterEvent = outboxStatus.toValueMap() } catch { print("Failed to parse and send outboxStatus event: \(error)") } - case HubPayload.EventName.DataStore.subscriptionsEstablished : + case HubPayload.EventName.DataStore.subscriptionsEstablished: do { - let subscriptionsEstablished = try FlutterSubscriptionsEstablishedEvent(payload: payload) + let subscriptionsEstablished = try FlutterSubscriptionsEstablishedEvent(payload: payload) flutterEvent = subscriptionsEstablished.toValueMap() } catch { print("Failed to parse and send subscriptionsEstablished event: \(error)") } - case HubPayload.EventName.DataStore.syncQueriesStarted : + case HubPayload.EventName.DataStore.syncQueriesStarted: do { - let syncQueriesStarted = try FlutterSyncQueriesStartedEvent(payload: payload) + let syncQueriesStarted = try FlutterSyncQueriesStartedEvent(payload: payload) flutterEvent = syncQueriesStarted.toValueMap() } catch { print("Failed to parse and send syncQueriesStarted event: \(error)") } - case HubPayload.EventName.DataStore.modelSynced : + case HubPayload.EventName.DataStore.modelSynced: do { let modelSynced = try FlutterModelSyncedEvent(payload: payload) flutterEvent = modelSynced.toValueMap() } catch { print("Failed to parse and send modelSynced event: \(error)") } - case HubPayload.EventName.DataStore.syncQueriesReady : + case HubPayload.EventName.DataStore.syncQueriesReady: do { - let syncQueriesReady = try FlutterSyncQueriesReadyEvent(payload: payload) + let syncQueriesReady = try FlutterSyncQueriesReadyEvent(payload: payload) flutterEvent = syncQueriesReady.toValueMap() } catch { print("Failed to parse and send syncQueriesReady event: \(error)") } - case HubPayload.EventName.DataStore.ready : + case HubPayload.EventName.DataStore.ready: do { let ready = try FlutterReadyEvent(payload: payload) flutterEvent = ready.toValueMap() } catch { print("Failed to parse and send ready event: \(error)") } - case HubPayload.EventName.DataStore.outboxMutationEnqueued : + case HubPayload.EventName.DataStore.outboxMutationEnqueued: do { guard let outboxMutationEnqueued = payload.data as? OutboxMutationEvent else { throw FlutterDataStoreError.hubEventCast } - let schemaRegistries = try self.ensureSchemaRegistries() + let schemaRegistries = try ensureSchemaRegistries() let flutterOutboxMutationEnqueued = try FlutterOutboxMutationEnqueuedEvent( outboxMutationEnqueued: outboxMutationEnqueued, eventName: payload.eventName, @@ -158,12 +157,12 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { } catch { print("Failed to parse and send outboxMutationEnqueued event: \(error)") } - case HubPayload.EventName.DataStore.outboxMutationProcessed : + case HubPayload.EventName.DataStore.outboxMutationProcessed: do { guard let outboxMutationProcessed = payload.data as? OutboxMutationEvent else { throw FlutterDataStoreError.hubEventCast } - let schemaRegistries = try self.ensureSchemaRegistries() + let schemaRegistries = try ensureSchemaRegistries() let flutterOutboxMutationProcessed = try FlutterOutboxMutationProcessedEvent( outboxMutationProcessed: outboxMutationProcessed, eventName: payload.eventName, @@ -179,7 +178,7 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { guard let eventData = payload.data as? MutationEvent else { throw FlutterDataStoreError.hubEventCast } - let schemaRegistries = try self.ensureSchemaRegistries() + let schemaRegistries = try ensureSchemaRegistries() let syncReceived = try FlutterSyncReceivedEvent( event: eventData, eventName: payload.eventName, @@ -195,7 +194,7 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { default: print("Unhandled DataStoreHubEvent: \(payload.eventName) \(payload.data ?? "")" ) } - + if let flutterEvent = flutterEvent { sendEvent(flutterEvent: flutterEvent) } @@ -206,7 +205,7 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { self.eventSink?(flutterEvent) } } - + public func onCancel(withArguments arguments: Any?) -> FlutterError? { eventSink = nil if let token = token { @@ -215,7 +214,7 @@ public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { token = nil return nil } - + deinit { if let token = token { Amplify.Hub.removeListener(token) diff --git a/packages/amplify_datastore/ios/Classes/DataStoreObserveEventStreamHandler.swift b/packages/amplify_datastore/ios/Classes/DataStoreObserveEventStreamHandler.swift index 1f97d0520e..e6f83b3027 100644 --- a/packages/amplify_datastore/ios/Classes/DataStoreObserveEventStreamHandler.swift +++ b/packages/amplify_datastore/ios/Classes/DataStoreObserveEventStreamHandler.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -16,15 +16,14 @@ import Foundation public class DataStoreObserveEventStreamHandler: NSObject, FlutterStreamHandler { - private var eventSink: FlutterEventSink? public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.eventSink = events + eventSink = events return nil } - func sendEvent(flutterEvent: [String : Any]) { + func sendEvent(flutterEvent: [String: Any]) { eventSink?(flutterEvent) } diff --git a/packages/amplify_datastore/ios/Classes/FlutterDataStoreError.swift b/packages/amplify_datastore/ios/Classes/FlutterDataStoreError.swift index 9f4628c78d..9d86851c02 100644 --- a/packages/amplify_datastore/ios/Classes/FlutterDataStoreError.swift +++ b/packages/amplify_datastore/ios/Classes/FlutterDataStoreError.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorHandler.swift b/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorHandler.swift index 55ef456dc2..13a7626e70 100644 --- a/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorHandler.swift +++ b/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorHandler.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,23 +19,23 @@ import AmplifyPlugins import amplify_core class FlutterDataStoreErrorHandler { - static func handleDataStoreError(error: DataStoreError, flutterResult: FlutterResult) { ErrorUtil.postErrorToFlutterChannel(result: flutterResult, errorCode: "DataStoreException", details: FlutterDataStoreErrorHandler.createSerializedError(error: error)) } - - static func createSerializedError(error: AmplifyError) -> Dictionary { + + static func createSerializedError(error: AmplifyError) -> [String: String] { return createSerializedError(message: error.errorDescription, recoverySuggestion: error.recoverySuggestion, underlyingError: error.underlyingError?.localizedDescription) } - + static func createSerializedError(message: String, recoverySuggestion: String?, - underlyingError: String?) -> Dictionary { - var serializedException: Dictionary = [:] + underlyingError: String?) -> [String: String] + { + var serializedException: [String: String] = [:] serializedException["message"] = message serializedException["recoverySuggestion"] = recoverySuggestion serializedException["underlyingException"] = underlyingError diff --git a/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorMessage.swift b/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorMessage.swift index 97feabeef4..2e57082986 100644 --- a/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorMessage.swift +++ b/packages/amplify_datastore/ios/Classes/FlutterDataStoreErrorMessage.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/packages/amplify_datastore/ios/Classes/FlutterDataStoreRequestUtils.swift b/packages/amplify_datastore/ios/Classes/FlutterDataStoreRequestUtils.swift index b5b2146f8b..48ccf32481 100644 --- a/packages/amplify_datastore/ios/Classes/FlutterDataStoreRequestUtils.swift +++ b/packages/amplify_datastore/ios/Classes/FlutterDataStoreRequestUtils.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -17,20 +17,19 @@ import Foundation import Amplify import AmplifyPlugins -public class FlutterDataStoreRequestUtils { - +public enum FlutterDataStoreRequestUtils { static func getJSONValue(_ jsonDict: [String: Any]) throws -> [String: JSONValue] { guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict) else { throw DataStoreError.decodingError("Unable to deserialize json data", "Check the model structure.") } - guard let jsonValue = try? JSONDecoder().decode(Dictionary.self, - from: jsonData) else { + guard let jsonValue = try? JSONDecoder().decode([String: JSONValue].self, + from: jsonData) + else { throw DataStoreError.decodingError("Unable to decode json value", "Check the model structure.") - } return jsonValue } - + static func getModelName(methodChannelArguments: [String: Any]) throws -> String { guard let modelName = methodChannelArguments["modelName"] as? String else { throw DataStoreError.decodingError( @@ -39,8 +38,8 @@ public class FlutterDataStoreRequestUtils { } return modelName } - - static func getModelSchema(modelSchemaRegistry: FlutterSchemaRegistry, modelName: String) throws -> ModelSchema { + + static func getModelSchema(modelSchemaRegistry: FlutterSchemaRegistry, modelName: String) throws -> ModelSchema { guard let modelSchema = modelSchemaRegistry.modelSchemas[modelName] else { throw DataStoreError.decodingError( "Schema for \(modelName) is not registered", @@ -50,9 +49,9 @@ public class FlutterDataStoreRequestUtils { } static func getCustomTypeSchema(customTypeSchemaRegistry: FlutterSchemaRegistry, modelName: String) throws -> ModelSchema { - return try(getModelSchema(modelSchemaRegistry: customTypeSchemaRegistry, modelName: modelName)) + return try (getModelSchema(modelSchemaRegistry: customTypeSchemaRegistry, modelName: modelName)) } - + static func getSerializedModelData(methodChannelArguments: [String: Any]) throws -> [String: Any] { guard let serializedModelData = methodChannelArguments["serializedModel"] as? [String: Any] else { throw DataStoreError.decodingError( @@ -61,7 +60,7 @@ public class FlutterDataStoreRequestUtils { } return serializedModelData } - + static func getModelID(serializedModelData: [String: Any]) throws -> String { guard let modelID = serializedModelData["id"] as? String else { throw DataStoreError.decodingError( diff --git a/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift b/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift index 688c6e5d4d..0ff8dd8dd3 100644 --- a/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift +++ b/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -12,30 +12,31 @@ * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ + import Amplify import Foundation // Contains the set of classes that conforms to the `Model` protocol. -final public class FlutterSchemaRegistry: AmplifyModelRegistration { +public final class FlutterSchemaRegistry: AmplifyModelRegistration { public var version: String = "" - + var modelSchemas: [String: ModelSchema] = [:] - + public func addModelSchema(modelName: String, modelSchema: ModelSchema) { modelSchemas[modelName] = modelSchema } - + public func registerModels(registry: ModelRegistry.Type) { modelSchemas.forEach { entry in ModelRegistry.register(modelType: FlutterSerializedModel.self, - modelSchema: entry.value) { (jsonString, decoder) -> Model in + modelSchema: entry.value) { jsonString, decoder -> Model in let resolvedDecoder: JSONDecoder if let decoder = decoder { resolvedDecoder = decoder } else { resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) } - + // Convert jsonstring to object let data = jsonString.data(using: .utf8)! let jsonValue = try resolvedDecoder.decode(JSONValue.self, from: data) @@ -43,14 +44,16 @@ final public class FlutterSchemaRegistry: AmplifyModelRegistration { var jsonObj: [String: JSONValue]? // the json string presents an array of objects if case .array(let jsonArray) = jsonValue, - case .object(let obj) = jsonArray[0] { + case .object(let obj) = jsonArray[0] + { jsonObj = obj } else if case .object(let obj) = jsonValue { jsonObj = obj } // the json string presents an object if let jsonObj = jsonObj, - case .string(let id) = jsonObj["id"] { + case .string(let id) = jsonObj["id"] + { let model = FlutterSerializedModel(id: id, map: jsonObj) return model } diff --git a/packages/amplify_datastore/ios/Classes/GetJsonValue.swift b/packages/amplify_datastore/ios/Classes/GetJsonValue.swift index 98a8529a10..48a3447b59 100644 --- a/packages/amplify_datastore/ios/Classes/GetJsonValue.swift +++ b/packages/amplify_datastore/ios/Classes/GetJsonValue.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ func getJSONValue(_ jsonDict: [String: Any]) throws -> [String: JSONValue] { guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict) else { throw DataStoreError.decodingError("Unable to deserialize json data", "Check the model structure.") } - guard let jsonValue = try? JSONDecoder().decode(Dictionary.self, - from: jsonData) else { + guard let jsonValue = try? JSONDecoder().decode([String: JSONValue].self, + from: jsonData) + else { throw DataStoreError.decodingError("Unable to decode json value", "Check the model structure.") - } return jsonValue } diff --git a/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift b/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift index eb9ceb6d83..fa9ae0c57e 100644 --- a/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift +++ b/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import Combine import amplify_core public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { - private let bridge: DataStoreBridge private let modelSchemaRegistry: FlutterSchemaRegistry private let customTypeSchemaRegistry: FlutterSchemaRegistry @@ -31,19 +30,20 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { private let dataStoreHubEventStreamHandler: DataStoreHubEventStreamHandler? private var channel: FlutterMethodChannel? private var observeSubscription: AnyCancellable? - + init(bridge: DataStoreBridge = DataStoreBridge(), modelSchemaRegistry: FlutterSchemaRegistry = FlutterSchemaRegistry(), customTypeSchemasRegistry: FlutterSchemaRegistry = FlutterSchemaRegistry(), dataStoreObserveEventStreamHandler: DataStoreObserveEventStreamHandler = DataStoreObserveEventStreamHandler(), - dataStoreHubEventStreamHandler: DataStoreHubEventStreamHandler = DataStoreHubEventStreamHandler()) { + dataStoreHubEventStreamHandler: DataStoreHubEventStreamHandler = DataStoreHubEventStreamHandler()) + { self.bridge = bridge self.modelSchemaRegistry = modelSchemaRegistry self.customTypeSchemaRegistry = customTypeSchemasRegistry self.dataStoreObserveEventStreamHandler = dataStoreObserveEventStreamHandler self.dataStoreHubEventStreamHandler = dataStoreHubEventStreamHandler } - + public static func register(with registrar: FlutterPluginRegistrar) { let instance = SwiftAmplifyDataStorePlugin() let observeChannel = FlutterEventChannel(name: "com.amazonaws.amplify/datastore_observe_events", binaryMessenger: registrar.messenger()) @@ -53,12 +53,12 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { hubChannel.setStreamHandler(instance.dataStoreHubEventStreamHandler) registrar.addMethodCallDelegate(instance, channel: instance.channel!) } - + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { let result = AtomicResult(result, call.method) var arguments: [String: Any] = [:] do { - if(call.arguments != nil) { + if call.arguments != nil { try arguments = checkArguments(args: call.arguments as Any) } } catch { @@ -66,7 +66,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult: result) return } - + switch call.method { case "configureDataStore": onConfigureDataStore(args: arguments, result: result) @@ -88,7 +88,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { result(FlutterMethodNotImplemented) } } - + private func getAuthModeStrategy(for strategyType: String?) throws -> AuthModeStrategyType { switch strategyType?.lowercased() { case "multiauth": @@ -102,13 +102,12 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { nil) } } - - private func onConfigureDataStore(args: [String: Any], result: @escaping FlutterResult) { + private func onConfigureDataStore(args: [String: Any], result: @escaping FlutterResult) { guard let serializedModelSchemas = args["modelSchemas"] as? [[String: Any]], let serializedCustomTypeSchemas = (args["customTypeSchemas"] ?? []) as? [[String: Any]], - let modelProviderVersion = args["modelProviderVersion"] as? String else { - + let modelProviderVersion = args["modelProviderVersion"] as? String + else { FlutterDataStoreErrorHandler.handleDataStoreError( error: DataStoreError.decodingError( @@ -119,19 +118,19 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { ) return } - + guard channel != nil else { return } - + let syncExpressionList = args["syncExpressions"] as? [[String: Any]] ?? [] let syncInterval = args["syncInterval"] as? Double ?? DataStoreConfiguration.defaultSyncInterval let syncMaxRecords = args["syncMaxRecords"] as? UInt ?? DataStoreConfiguration.defaultSyncMaxRecords let syncPageSize = args["syncPageSize"] as? UInt ?? DataStoreConfiguration.defaultSyncPageSize - + do { let authModeStrategy = try getAuthModeStrategy(for: args["authModeStrategy"] as? String) - + let customTypeSchemaDependenciesOrder = try getCustomTypeSchemasDependenciesOrder( serializedCustomTypeSchemas: serializedCustomTypeSchemas ) @@ -143,8 +142,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { let modelSchemas: [ModelSchema] = try serializedModelSchemas.map { try FlutterModelSchema.init(serializedData: $0).convertToNativeModelSchema(customTypeSchemasRegistry: self.customTypeSchemaRegistry) } - - modelSchemas.forEach { (modelSchema) in + + modelSchemas.forEach { modelSchema in modelSchemaRegistry.addModelSchema(modelName: modelSchema.name, modelSchema: modelSchema) } @@ -152,13 +151,13 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { let syncExpressions: [DataStoreSyncExpression] = try createSyncExpressions(syncExpressionList: syncExpressionList) - self.dataStoreHubEventStreamHandler?.registerModelsForHub( + dataStoreHubEventStreamHandler?.registerModelsForHub( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry ) - - var errorHandler:DataStoreErrorHandler = createErrorHandler(args: args) - var conflictHandler:DataStoreConflictHandler = createConflictHandler(args: args) + + var errorHandler: DataStoreErrorHandler = createErrorHandler(args: args) + var conflictHandler: DataStoreConflictHandler = createConflictHandler(args: args) let dataStorePlugin = AWSDataStorePlugin(modelRegistration: modelSchemaRegistry, configuration: .custom( @@ -170,23 +169,23 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { syncExpressions: syncExpressions, authModeStrategy: authModeStrategy)) try Amplify.add(plugin: dataStorePlugin) - + Amplify.Logging.logLevel = .info print("Amplify configured with DataStore plugin") result(true) - } catch ModelSchemaError.parse(let className, let fieldName, let desiredType){ + } catch ModelSchemaError.parse(let className, let fieldName, let desiredType) { FlutterDataStoreErrorHandler.handleDataStoreError( error: DataStoreError.decodingError( "Invalid modelSchema " + className + "-" + fieldName + " cannot be cast to " + desiredType, ErrorMessages.missingRecoverySuggestion), flutterResult: result) return - } catch let error { - if(error is DataStoreError){ + } catch { + if error is DataStoreError{ FlutterDataStoreErrorHandler.handleDataStoreError( error: error as! DataStoreError, flutterResult: result) - } else if(error is ConfigurationError) { + } else if error is ConfigurationError { let configError = error as! ConfigurationError var errorCode = "DataStoreException" if case .amplifyAlreadyConfigured = configError { @@ -196,8 +195,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { result: result, errorCode: errorCode, details: [ - "message" : configError.errorDescription, - "recoverySuggestion" : configError.recoverySuggestion, + "message": configError.errorDescription, + "recoverySuggestion": configError.recoverySuggestion, "underlyingError": configError.underlyingError != nil ? configError.underlyingError!.localizedDescription : "" ] ) @@ -207,25 +206,23 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { } return } - } - + func onQuery(args: [String: Any], flutterResult: @escaping FlutterResult) { - do { let modelName = try FlutterDataStoreRequestUtils.getModelName(methodChannelArguments: args) let modelSchema = try FlutterDataStoreRequestUtils.getModelSchema( modelSchemaRegistry: modelSchemaRegistry, modelName: modelName ) - let queryPredicates = try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String : Any]) + let queryPredicates = try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String: Any]) let querySortInput = try QuerySortBuilder.fromSerializedList(args["querySort"] as? [[String: Any]]) let queryPagination = QueryPaginationBuilder.fromSerializedMap(args["queryPagination"] as? [String: Any]) try bridge.onQuery(FlutterSerializedModel.self, modelSchema: modelSchema, where: queryPredicates, sort: querySortInput, - paginate: queryPagination) { (result) in + paginate: queryPagination) { result in switch result { case .failure(let error): print("Query API failed. Error = \(error)") @@ -233,7 +230,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult: flutterResult) case .success(let res): do { - let serializedResults = try res.map { (queryResult) -> [String: Any] in + let serializedResults = try res.map { queryResult -> [String: Any] in return try queryResult.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, @@ -264,7 +261,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult: flutterResult) } } - + // Initial Save fails for QueryPredicate.all, so we must pass nil instead // TODO: Amplify iOS should change .all initial save behavior to work. // Afterwards, we can remove this function and safely pass .all as our default queryPredicates @@ -278,27 +275,26 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { } return queryPredicates } - + func onSave(args: [String: Any], flutterResult: @escaping FlutterResult) { - do { let modelName = try FlutterDataStoreRequestUtils.getModelName(methodChannelArguments: args) let modelSchema = try FlutterDataStoreRequestUtils.getModelSchema( modelSchemaRegistry: modelSchemaRegistry, modelName: modelName ) - let queryPredicates = filterQueryPredicateAll(queryPredicates: try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String : Any])) - + let queryPredicates = filterQueryPredicateAll(queryPredicates: try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String: Any])) + let serializedModelData = try FlutterDataStoreRequestUtils.getSerializedModelData(methodChannelArguments: args) let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: serializedModelData) - + let serializedModel = FlutterSerializedModel(id: modelID, map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData)) - + try bridge.onSave( serializedModel: serializedModel, modelSchema: modelSchema, where: queryPredicates - ) { (result) in + ) { result in switch result { case .failure(let error): print("Save API failed. Error: \(error)") @@ -310,20 +306,18 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult(nil) } } - } - catch let error as DataStoreError { + } catch let error as DataStoreError { print("Failed to parse save arguments with \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) - } - catch { + } catch { print("An unexpected error occurred when parsing save arguments: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) } } - + func onDelete(args: [String: Any], flutterResult: @escaping FlutterResult) { do { let modelName = try FlutterDataStoreRequestUtils.getModelName(methodChannelArguments: args) @@ -331,18 +325,18 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { modelSchemaRegistry: modelSchemaRegistry, modelName: modelName ) - let queryPredicatesMap = args["queryPredicate"] as? [String : Any]; - let queryPredicates = queryPredicatesMap != nil ? try QueryPredicateBuilder.fromSerializedMap(queryPredicatesMap) : nil; - + let queryPredicatesMap = args["queryPredicate"] as? [String: Any] + let queryPredicates = queryPredicatesMap != nil ? try QueryPredicateBuilder.fromSerializedMap(queryPredicatesMap) : nil + let serializedModelData = try FlutterDataStoreRequestUtils.getSerializedModelData(methodChannelArguments: args) let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: serializedModelData) - + let serializedModel = FlutterSerializedModel(id: modelID, map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData)) - + try bridge.onDelete( serializedModel: serializedModel, modelSchema: modelSchema, - where: queryPredicates) { (result) in + where: queryPredicates) { result in switch result { case .failure(let error): print("Delete API failed. Error = \(error)") @@ -352,22 +346,19 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult(nil) } } - - } - catch let error as DataStoreError { + } catch let error as DataStoreError { print("Failed to parse delete arguments with \(error)") FlutterDataStoreErrorHandler.handleDataStoreError( error: error, flutterResult: flutterResult) - } - catch { + } catch { print("An unexpected error occured when parsing delete arguments: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) return } } - + public func onSetUpObserve(flutterResult: @escaping FlutterResult) { do { observeSubscription = try observeSubscription ?? bridge.onObserve().sink { completion in @@ -380,8 +371,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { case .finished: print("finished") } - - } receiveValue: { (mutationEvent) in + + } receiveValue: { mutationEvent in do { let serializedEvent = try mutationEvent.decodeModel(as: FlutterSerializedModel.self) guard let eventType = EventType(rawValue: mutationEvent.mutationType) else { @@ -409,10 +400,10 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult(false) } } - + func onClear(flutterResult: @escaping FlutterResult) { do { - try bridge.onClear() {(result) in + try bridge.onClear {result in switch result { case .failure(let error): print("Clear API failed. Error: \(error)") @@ -424,8 +415,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult(nil) } } - } - catch { + } catch { print("An unexpected error occured: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) @@ -434,7 +424,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { func onStart(flutterResult: @escaping FlutterResult) { do { - try bridge.onStart() { (result) in + try bridge.onStart { result in switch result { case .failure(let error): print("Start API failed. Error: \(error)") @@ -446,8 +436,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult(nil) } } - } - catch { + } catch { print("An unexpected error occured: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) @@ -456,7 +445,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { func onStop(flutterResult: @escaping FlutterResult) { do { - try bridge.onStop() { (result) in + try bridge.onStop { result in switch result { case .failure(let error): print("Stop API failed. Error: \(error)") @@ -468,22 +457,21 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult(nil) } } - } - catch { + } catch { print("An unexpected error occured: \(error)") FlutterDataStoreErrorHandler.handleDataStoreError(error: DataStoreError(error: error), flutterResult: flutterResult) } } - + private func checkArguments(args: Any) throws -> [String: Any] { guard let res = args as? [String: Any] else { throw DataStoreError.decodingError("Flutter method call arguments are not a map.", "Check the values that are being passed from Dart.") } - return res; + return res } - + private func createSyncExpressions(syncExpressionList: [[String: Any]]) throws -> [DataStoreSyncExpression] { return try syncExpressionList.map { syncExpression in let id = syncExpression["id"] as! String @@ -532,7 +520,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { FlutterDataStoreErrorRecoverySuggestion.decoding.rawValue ) } - if (!customTypeSchemaDependenciesOrder.contains(schemaName)) { + if !customTypeSchemaDependenciesOrder.contains(schemaName) { let schema: ModelSchema = try FlutterModelSchema.init(serializedData: serializedCustomTypeSchema) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemaRegistry) customTypeSchemaRegistry.addModelSchema(modelName: schemaName, modelSchema: schema) @@ -562,14 +550,14 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { ) } - if (type["fieldType"] == "embedded" || type["fieldType"] == "embeddedCollection") { + if type["fieldType"] == "embedded" || type["fieldType"] == "embeddedCollection" { guard let schemaName = serializedCustomTypeSchema["name"] as? String else { throw DataStoreError.decodingError( "Cannot get schema name.", FlutterDataStoreErrorRecoverySuggestion.decoding.rawValue ) } - if (schemasDependencies[schemaName] == nil) { + if schemasDependencies[schemaName] == nil { schemasDependencies[schemaName] = [] } guard let customTypeName = type["ofCustomTypeName"] else { @@ -583,11 +571,11 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { } } - var result: [String] = []; + var result: [String] = [] var unresolved: Set = [] for node in schemasDependencies.keys { - if (result.contains(node)) { + if result.contains(node) { continue } try resolveCustomTypeSchemaOrder( @@ -609,8 +597,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { ) throws { unresolved.insert(startNode) for node in dependenciesMap[startNode] ?? [] { - if (!result.contains(node)) { - if (unresolved.contains(node)) { + if !result.contains(node) { + if unresolved.contains(node) { throw DataStoreError.configuration( "Cicularly dependent schemas are not supported.", "Please check schema definition and avoid cicular dependencies." @@ -633,15 +621,15 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { func getPlugin() throws -> AWSDataStorePlugin { return try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin } - - func createErrorHandler(args: [String: Any]) -> DataStoreErrorHandler { + + func createErrorHandler(args: [String: Any]) -> DataStoreErrorHandler { var errorHandler: DataStoreErrorHandler - if((args["hasErrorHandler"] as? Bool) == true) { + if (args["hasErrorHandler"] as? Bool) == true { errorHandler = { error in - let map : [String:Any] = [ - "errorCode" : "DataStoreException", - "errorMesage" : ErrorMessages.defaultFallbackErrorMessage, - "details" : FlutterDataStoreErrorHandler.createSerializedError(error: error) + let map: [String: Any] = [ + "errorCode": "DataStoreException", + "errorMesage": ErrorMessages.defaultFallbackErrorMessage, + "details": FlutterDataStoreErrorHandler.createSerializedError(error: error) ] DispatchQueue.main.async { self.channel!.invokeMethod("errorHandler", arguments: map) @@ -654,10 +642,10 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { } return errorHandler } - - func createConflictHandler(args: [String: Any]) -> DataStoreConflictHandler { - var conflictHandler:DataStoreConflictHandler - if((args["hasConflictHandler"] as? Bool) == true) { + + func createConflictHandler(args: [String: Any]) -> DataStoreConflictHandler { + var conflictHandler: DataStoreConflictHandler + if (args["hasConflictHandler"] as? Bool) == true { conflictHandler = { conflictData, onDecision in do { guard @@ -668,57 +656,56 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { throw DataStoreError.decodingError("Native ConflictData is invalid", "Check the values in ConflictData object.") } - let map : [String:Any] = [ - "modelName" : modelName, - "local" : try local.toMap( + let map: [String: Any] = [ + "modelName": modelName, + "local": try local.toMap( modelSchemaRegistry: self.modelSchemaRegistry, customTypeSchemaRegistry: self.customTypeSchemaRegistry, modelName: modelName), - "remote" : try remote.toMap( + "remote": try remote.toMap( modelSchemaRegistry: self.modelSchemaRegistry, customTypeSchemaRegistry: self.customTypeSchemaRegistry, modelName: modelName) ] DispatchQueue.main.async { - self.channel!.invokeMethod("conflictHandler", arguments: map){ result in + self.channel!.invokeMethod("conflictHandler", arguments: map) { result in do { guard - let resultMap : [String: Any] = result as? [String: Any], + let resultMap: [String: Any] = result as? [String: Any], let resolutionStrategy = resultMap["resolutionStrategy"] as? String else { throw DataStoreError.decodingError("Flutter resultMap is invalid", "Check the values that are being passed from Dart.") } - - switch(resolutionStrategy){ + + switch resolutionStrategy{ case "applyRemote": onDecision(.applyRemote) case "retryLocal": onDecision(.retryLocal) case "retry": - guard let modelMap = resultMap["customModel"] as? [String : Any] + guard let modelMap = resultMap["customModel"] as? [String: Any] else { throw DataStoreError.decodingError("Flutter CustomModel map is invalid", "Check the values that are being passed from Dart.") } let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: modelMap) - let serializedModel = try FlutterSerializedModel(id: modelID, map: FlutterDataStoreRequestUtils.getJSONValue(modelMap)) + let serializedModel = try FlutterSerializedModel(id: modelID, map: FlutterDataStoreRequestUtils.getJSONValue(modelMap)) onDecision(.retry(serializedModel)) default: print("Unrecognized resolutionStrategy to resolve conflict. Applying default conflict resolution, applyRemote.") onDecision(.applyRemote) } - } - catch let error { + } catch { print("Error in conflict handler: \(error) Applying default conflict resolution, applyRemote.") onDecision(.applyRemote) } } } - } catch let error { + } catch { print("Error in conflict handler: \(error) Applying default conflict resolution, applyRemote.") onDecision(.applyRemote) } } } else { - conflictHandler = { _, resolve in + conflictHandler = { _, resolve in resolve(.applyRemote) } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubElement.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubElement.swift index 6e72be242f..be1a3a038a 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubElement.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubElement.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -22,12 +22,11 @@ import AWSCore import Combine public struct FlutterHubElement { - var model: [String: Any] var version: Int? var lastChangedAt: Int? var deleted: Bool - + init( hubElement: OutboxMutationEvent.OutboxMutationEventElement, modelSchemaRegistry: FlutterSchemaRegistry, @@ -57,7 +56,7 @@ public struct FlutterHubElement { guard let decodedModel = (try ModelRegistry.decode(modelName: modelName, from: hubElement.json) as? FlutterSerializedModel) else { throw FlutterDataStoreError.hubEventCast } - model = try decodedModel.toMap( + self.model = try decodedModel.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, modelName: modelName @@ -72,21 +71,19 @@ public struct FlutterHubElement { } else if let value = serializedData["_lastChangedAt"] as? Int { self.lastChangedAt = value } - } - catch { + } catch { throw FlutterDataStoreError.hubEventCast } } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "model": self.model, + "model": model, "syncMetadata": [ - "_version": self.version as Any, - "_lastChangedAt": self.lastChangedAt as Any, - "_deleted": self.deleted as Any + "_version": version as Any, + "_lastChangedAt": lastChangedAt as Any, + "_deleted": deleted as Any ] ] } } - diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubEvent.swift index 2fd831a59f..ff81a7a2dd 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterHubEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ import Foundation protocol FlutterHubEvent { var eventName: String { get set } - func toValueMap() -> Dictionary + func toValueMap() -> [String: Any] } func shortEventName(eventName: String) -> String { diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterModelSyncedEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterModelSyncedEvent.swift index 4b202e8983..1950227ef4 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterModelSyncedEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterModelSyncedEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ struct FlutterModelSyncedEvent: FlutterHubEvent { var added: Int var updated: Int var deleted: Int - + init(payload: HubPayload) throws { guard let modelSynced = payload.data as? ModelSyncedEvent else { throw FlutterDataStoreError.hubEventCast @@ -38,16 +38,16 @@ struct FlutterModelSyncedEvent: FlutterHubEvent { self.updated = modelSynced.updated self.deleted = modelSynced.deleted } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "model": self.modelName, - "isFullSync": self.isFullSync, - "isDeltaSync": self.isDeltaSync, - "added": self.added, - "updated": self.updated, - "deleted": self.deleted + "eventName": eventName, + "model": modelName, + "isFullSync": isFullSync, + "isDeltaSync": isDeltaSync, + "added": added, + "updated": updated, + "deleted": deleted ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterNetworkStatusEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterNetworkStatusEvent.swift index 5a877fd8b6..93333086ec 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterNetworkStatusEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterNetworkStatusEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import AmplifyPlugins struct FlutterNetworkStatusEvent: FlutterHubEvent { var eventName: String var active: Bool - + init(payload: HubPayload) throws { guard let networkStatus = payload.data as? NetworkStatusEvent else { throw FlutterDataStoreError.hubEventCast @@ -28,11 +28,11 @@ struct FlutterNetworkStatusEvent: FlutterHubEvent { self.eventName = shortEventName(eventName: payload.eventName) self.active = networkStatus.active } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "active": self.active + "eventName": eventName, + "active": active ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationEnqueuedEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationEnqueuedEvent.swift index 7d615f9301..2d2c4b6b27 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationEnqueuedEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationEnqueuedEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import AmplifyPlugins struct FlutterOutboxMutationEnqueuedEvent: FlutterHubEvent { var eventName: String var modelName: String - var element: FlutterHubElement - + var element: FlutterHubElement + init( outboxMutationEnqueued: OutboxMutationEvent, eventName: String, @@ -35,19 +35,18 @@ struct FlutterOutboxMutationEnqueuedEvent: FlutterHubEvent { hubElement: outboxMutationEnqueued.element, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, - modelName: self.modelName + modelName: modelName ) } catch { throw FlutterDataStoreError.acquireSchemaForHub } - } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "modelName": self.modelName, - "element": self.element.toValueMap() as Any + "eventName": eventName, + "modelName": modelName, + "element": element.toValueMap() as Any ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationProcessedEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationProcessedEvent.swift index 00d6ad904c..fefb19b72d 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationProcessedEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxMutationProcessedEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import Combine struct FlutterOutboxMutationProcessedEvent: FlutterHubEvent { var eventName: String var modelName: String - var element: FlutterHubElement - + var element: FlutterHubElement + init( outboxMutationProcessed: OutboxMutationEvent, eventName: String, @@ -37,18 +37,18 @@ struct FlutterOutboxMutationProcessedEvent: FlutterHubEvent { hubElement: outboxMutationProcessed.element, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, - modelName: self.modelName + modelName: modelName ) } catch { throw FlutterDataStoreError.acquireSchemaForHub } } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "modelName": self.modelName, - "element": self.element.toValueMap() as Any + "eventName": eventName, + "modelName": modelName, + "element": element.toValueMap() as Any ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxStatusEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxStatusEvent.swift index 78170b55fd..90f8ce9de3 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxStatusEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterOutboxStatusEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import AmplifyPlugins struct FlutterOutboxStatusEvent: FlutterHubEvent { var eventName: String var isEmpty: Bool - + init(payload: HubPayload) throws { guard let outboxStatus = payload.data as? OutboxStatusEvent else { throw FlutterDataStoreError.hubEventCast @@ -28,11 +28,11 @@ struct FlutterOutboxStatusEvent: FlutterHubEvent { self.eventName = shortEventName(eventName: payload.eventName) self.isEmpty = outboxStatus.isEmpty } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "isEmpty": self.isEmpty + "eventName": eventName, + "isEmpty": isEmpty ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterReadyEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterReadyEvent.swift index 4d99eb676b..b1cdf4de88 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterReadyEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterReadyEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,14 +19,14 @@ import AmplifyPlugins struct FlutterReadyEvent: FlutterHubEvent { var eventName: String - + init(payload: HubPayload) throws { self.eventName = shortEventName(eventName: payload.eventName) } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, + "eventName": eventName, ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSubscriptionsEstablishedEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSubscriptionsEstablishedEvent.swift index 45332c2bfb..2181c36d38 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSubscriptionsEstablishedEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSubscriptionsEstablishedEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,14 +19,14 @@ import AmplifyPlugins struct FlutterSubscriptionsEstablishedEvent: FlutterHubEvent { var eventName: String - + init(payload: HubPayload) throws { self.eventName = shortEventName(eventName: payload.eventName) } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, + "eventName": eventName, ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesReadyEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesReadyEvent.swift index 903a527635..914c049c04 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesReadyEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesReadyEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,14 +19,14 @@ import AmplifyPlugins struct FlutterSyncQueriesReadyEvent: FlutterHubEvent { var eventName: String - + init(payload: HubPayload) throws { self.eventName = shortEventName(eventName: payload.eventName) } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, + "eventName": eventName, ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesStartedEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesStartedEvent.swift index abfa2c4729..1290651296 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesStartedEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncQueriesStartedEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import AmplifyPlugins struct FlutterSyncQueriesStartedEvent: FlutterHubEvent { var eventName: String var models: [String] - + init(payload: HubPayload) throws { guard let syncQueriesStarted = payload.data as? SyncQueriesStartedEvent else { throw FlutterDataStoreError.hubEventCast @@ -28,11 +28,11 @@ struct FlutterSyncQueriesStartedEvent: FlutterHubEvent { self.eventName = shortEventName(eventName: payload.eventName) self.models = syncQueriesStarted.models } - - func toValueMap() -> Dictionary { + + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "models": self.models.description + "eventName": eventName, + "models": models.description ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncReceivedEvent.swift b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncReceivedEvent.swift index b0c1ca4738..ebc1fc480e 100644 --- a/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncReceivedEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/hub/FlutterSyncReceivedEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import AmplifyPlugins struct FlutterSyncReceivedEvent: FlutterHubEvent { var eventName: String var modelName: String - var element: FlutterHubElement + var element: FlutterHubElement init( event: MutationEvent, @@ -38,11 +38,11 @@ struct FlutterSyncReceivedEvent: FlutterHubEvent { } } - func toValueMap() -> Dictionary { + func toValueMap() -> [String: Any] { return [ - "eventName": self.eventName, - "modelName": self.modelName, - "element": self.element.toValueMap() + "eventName": eventName, + "modelName": modelName, + "element": element.toValueMap() ] } } diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterAuthRule.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterAuthRule.swift index 1e005e6bbf..43b8b07b6e 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterAuthRule.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterAuthRule.swift @@ -1,34 +1,32 @@ /* -* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ import Foundation import Amplify public struct FlutterAuthRule { - - private var authStrategy : String - private let ownerField : String? - private let identityClaim : String? - private let groupClaim : String? - private let groups : [String]? - private let groupsField : String? + private var authStrategy: String + private let ownerField: String? + private let identityClaim: String? + private let groupClaim: String? + private let groups: [String]? + private let groupsField: String? private let provider: String? - private var operations : [String]? - - init(serializedData: [String: Any]) throws { + private var operations: [String]? + init(serializedData: [String: Any]) throws { guard let authStrategy = serializedData["authStrategy"] as? String else { throw ModelSchemaError.parse( @@ -38,22 +36,22 @@ public struct FlutterAuthRule { } self.authStrategy = authStrategy - + self.ownerField = serializedData["ownerField"] as? String self.identityClaim = serializedData["identityClaim"] as? String - + self.groupClaim = serializedData["groupClaim"] as? String - + self.groups = serializedData["groups"] as? [String] - + self.groupsField = serializedData["groupsField"] as? String self.provider = serializedData["provider"] as? String self.operations = serializedData["operations"] as? [String] } - + private func stringToAuthStrategy(authStrategyString: String) -> AuthStrategy{ switch authStrategyString { case "OWNER": @@ -85,7 +83,7 @@ public struct FlutterAuthRule { return nil } } - + private func stringToModelOperation(modelOperationString: String) -> ModelOperation{ switch modelOperationString { case "CREATE": @@ -100,7 +98,7 @@ public struct FlutterAuthRule { preconditionFailure("Could not create a ModelOperation from \(modelOperationString)") } } - + public func convertToNativeAuthRule() -> AuthRule{ return AuthRule( allow: stringToAuthStrategy(authStrategyString: authStrategy), @@ -110,10 +108,9 @@ public struct FlutterAuthRule { groups: groups ?? [String](), groupsField: groupsField, provider: stringToAuthProvider(providerString: provider), - operations: (operations)?.map { + operations: operations?.map { stringToModelOperation(modelOperationString: $0) } ?? [ModelOperation]() ) } - } diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift index 430527d860..7fe0d5fdba 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift @@ -1,29 +1,27 @@ /* -* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ import Foundation import Amplify public struct FlutterModelAssociation { - - private let associationType : String - private let targetName : String? + private let associationType: String + private let targetName: String? private let associatedName: String? init(serializedData: [String: Any]) throws { - guard let associationType = serializedData["associationType"] as? String else { throw ModelSchemaError.parse( @@ -32,13 +30,12 @@ public struct FlutterModelAssociation { desiredType: "String") } self.associationType = associationType - + self.targetName = serializedData["targetName"] as? String self.associatedName = serializedData["associatedName"] as? String } - + public func convertToNativeModelAssociation() -> ModelAssociation{ - switch associationType { case "HasMany": return ModelAssociation.hasMany(associatedFieldName: associatedName) diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelField.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelField.swift index dc47346b25..2bee1f82f3 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelField.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelField.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ import Foundation import Amplify public struct FlutterModelField { - public let name: String public let type: FlutterModelFieldType public let isRequired: Bool @@ -26,9 +25,8 @@ public struct FlutterModelField { public let isReadOnly: Bool public let association: FlutterModelAssociation? public let authRules: [FlutterAuthRule]? - - init(serializedData: [String: Any]) throws { + init(serializedData: [String: Any]) throws { guard let name = serializedData["name"] as? String else { throw ModelSchemaError.parse( @@ -63,7 +61,7 @@ public struct FlutterModelField { desiredType: "Bool") } self.isArray = isArray - + guard let isReadOnly = serializedData["isReadOnly"] as? Bool else { throw ModelSchemaError.parse( @@ -73,19 +71,17 @@ public struct FlutterModelField { } self.isReadOnly = isReadOnly - if let inputAssociationMap = serializedData["association"] as? [String : Any]{ + if let inputAssociationMap = serializedData["association"] as? [String: Any] { self.association = try FlutterModelAssociation(serializedData: inputAssociationMap) - } - else{ + } else{ self.association = nil } - if let inputAuthRulesMap = serializedData["authRules"] as? [[String:String]]{ + if let inputAuthRulesMap = serializedData["authRules"] as? [[String: String]] { self.authRules = try inputAuthRulesMap.map{ try FlutterAuthRule(serializedData: $0) } - } - else{ + } else{ self.authRules = nil } } @@ -125,19 +121,17 @@ public struct FlutterModelField { preconditionFailure("Could not create a ModelFieldType from \(String(describing: type)) MetaType") } - private func convertFlutterAuthRules(flutterAuthRules : [FlutterAuthRule]?) -> [AuthRule]?{ - + private func convertFlutterAuthRules(flutterAuthRules: [FlutterAuthRule]?) -> [AuthRule]?{ if let flutterAuthRules = flutterAuthRules{ - var result: [AuthRule] = [AuthRule](); + var result = [AuthRule]() for flutterAuthRule in flutterAuthRules { - result.append( flutterAuthRule.convertToNativeAuthRule() ); + result.append( flutterAuthRule.convertToNativeAuthRule() ) } - return result; - } - else{ - return nil; + return result + } else{ + return nil } } @@ -154,7 +148,6 @@ public struct FlutterModelField { } ?? [AuthRule]() ) } - } typealias FlutterModelFields = [String: FlutterModelField] diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelFieldType.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelFieldType.swift index 71f2633a1a..90601217eb 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelFieldType.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelFieldType.swift @@ -1,31 +1,28 @@ /* -* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ import Foundation import Amplify import amplify_core public struct FlutterModelFieldType { - public let fieldType : String - public let ofModelName : String? + public let fieldType: String + public let ofModelName: String? public let ofCustomTypeName: String? - - + init(serializedData: [String: Any]) throws { - guard let fieldType = serializedData["fieldType"] as? String else { throw ModelSchemaError.parse( @@ -34,13 +31,12 @@ public struct FlutterModelFieldType { desiredType: "String") } self.fieldType = fieldType - + self.ofModelName = serializedData["ofModelName"] as? String self.ofCustomTypeName = serializedData["ofCustomTypeName"] as? String } - + public func convertToNativeModelField(customTypeSchemaRegistry: FlutterSchemaRegistry) throws -> ModelFieldType { - switch fieldType { case "string": return ModelFieldType.string @@ -69,7 +65,7 @@ public struct FlutterModelFieldType { desiredType: "String") } return ModelFieldType.model(name: ofModelName) - case "collection" : + case "collection": guard let ofModelName = ofModelName else { throw ModelSchemaError.parse( @@ -84,7 +80,7 @@ public struct FlutterModelFieldType { return ModelFieldType.collection(of: ofModelName) } case "embedded": - guard let customTypeName = self.ofCustomTypeName else { + guard let customTypeName = ofCustomTypeName else { throw FlutterDataStoreError.acquireSchemaForHub } // For embedded CustomType, link its schema to the FieldType @@ -96,7 +92,7 @@ public struct FlutterModelFieldType { ) ) case "embeddedCollection": - guard let customTypeName = self.ofCustomTypeName else { + guard let customTypeName = ofCustomTypeName else { throw FlutterDataStoreError.acquireSchemaForHub } // For embedded CustomType, link its schema to the FieldType diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift index 8f22c67c72..af1accc9be 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -18,17 +18,15 @@ import Foundation import Amplify struct FlutterModelSchema { - let name: String let fields: [String: FlutterModelField] let pluralName: String? let authRules: [FlutterAuthRule]? - + // Not used for now let attributes: [ModelAttribute] = [] - + init(serializedData: [String: Any]) throws { - guard let name = serializedData["name"] as? String else { throw ModelSchemaError.parse( className: "FlutterModelSchema", @@ -36,7 +34,7 @@ struct FlutterModelSchema { desiredType: "String") } self.name = name - + guard let inputFieldsMap = serializedData["fields"] as? [String: [String: Any]] else { throw ModelSchemaError.parse( className: "FlutterModelSchema", @@ -48,19 +46,16 @@ struct FlutterModelSchema { } self.pluralName = serializedData["pluralName"] as? String - - if let inputAuthRulesMap = serializedData["authRules"] as? [[String:Any]]{ + + if let inputAuthRulesMap = serializedData["authRules"] as? [[String: Any]] { self.authRules = try inputAuthRulesMap.map { try FlutterAuthRule(serializedData: $0) } - } - else { + } else { self.authRules = nil } - - } - + public func convertToNativeModelSchema(customTypeSchemasRegistry: FlutterSchemaRegistry) throws -> ModelSchema { return ModelSchema.init( name: name, diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift index 0cace48d3e..c69b1a0652 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -28,9 +28,8 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } public init(from decoder: Decoder) throws { - let y = try decoder.container(keyedBy: CodingKeys.self) - id = try y.decode(String.self, forKey: .id) + self.id = try y.decode(String.self, forKey: .id) let json = try JSONValue(from: decoder) let typeName = json["__typename"] @@ -40,12 +39,11 @@ struct FlutterSerializedModel: Model, JSONValueHolder { v["__typename"] = typeName values = v } else { - values = [:] + self.values = [:] } } private static func removeReservedNames(_ jsonValue: JSONValue) -> JSONValue { - if case .object(let jsonObject) = jsonValue { var modifiedJsonValue: [String: JSONValue] = [:] @@ -58,7 +56,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { return .object(modifiedJsonValue) } if case .array(let jsonArray) = jsonValue { - var modifiedArray:[JSONValue] = [] + var modifiedArray: [JSONValue] = [] for item in jsonArray { let modifiedItem = removeReservedNames(item) modifiedArray.append(modifiedItem) @@ -102,7 +100,6 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } private static func extractJsonValue(key: String, value: JSONValue?, modelSchema: ModelSchema, returnTemporalType: Bool = true) -> Any?? { - let field = modelSchema.field(withName: key) switch (field?.type, value) { case (.int, .number(let deserializedValue)): @@ -110,7 +107,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { case (.dateTime, .string(let deserializedValue)), (.date, .string(let deserializedValue)), (.time, .string(let deserializedValue)): // If returning value for Amplify iOS library return FlutterTemporal - if(returnTemporalType) { + if returnTemporalType { return FlutterTemporal(iso8601String: deserializedValue) } // Else returning value to be serialized to Flutter layer @@ -121,26 +118,30 @@ struct FlutterSerializedModel: Model, JSONValueHolder { case (.timestamp, .number(let deserializedValue)): return Int(deserializedValue) default: - return extractJsonValue(value: value); + return extractJsonValue(value: value) } } private static func deserializeValue(value: JSONValue?, fieldType: Codable.Type) -> Any?? { - if fieldType is Int.Type, - case .some(.number(let deserializedValue)) = value { + case .some(.number(let deserializedValue)) = value + { return Int(deserializedValue) } else if fieldType is Temporal.DateTime.Type, - case .some(.string(let deserializedValue)) = value { + case .some(.string(let deserializedValue)) = value + { return deserializedValue } else if fieldType is Temporal.Date.Type, - case .some(.string(let deserializedValue)) = value { + case .some(.string(let deserializedValue)) = value + { return deserializedValue } else if fieldType is Temporal.Time.Type, - case .some(.string(let deserializedValue)) = value { + case .some(.string(let deserializedValue)) = value + { return deserializedValue } else if fieldType is Int64.Type, - case .some(.number(let deserializedValue)) = value { + case .some(.number(let deserializedValue)) = value + { return Int(deserializedValue) } @@ -193,7 +194,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry, modelName: String - ) throws -> [String: Any]{ + ) throws -> [String: Any] { let modelSchema = try FlutterSerializedModel.getSchema( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, @@ -201,21 +202,22 @@ struct FlutterSerializedModel: Model, JSONValueHolder { ) var result = [String: Any]() - for(key, value) in values { + for (key, value) in values { let field = modelSchema.field(withName: key) - if(value == nil){ + if value == nil{ continue } if case .object(let deserializedValue) = value { // If a field that has many models - if (deserializedValue["associatedField"] != nil && deserializedValue["associatedId"] != nil) { - result[key] = nil; + if deserializedValue["associatedField"] != nil && deserializedValue["associatedId"] != nil { + result[key] = nil } // If a field that has one or belongs to a model else if case .string(let modelId) = deserializedValue["id"], - case .model(let nextModelName) = field!.type { + case .model(let nextModelName) = field!.type + { result[key] = [ "id": modelId, "modelName": nextModelName, @@ -229,7 +231,8 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } // if a field has a single CustomType value presented as JSONValue.object else if case .embedded(_, .some(let customTypeSchema)) = field?.type, - case .some(.object(let deserializedValue)) = values[key] { + case .some(.object(let deserializedValue)) = values[key] + { let customTypeName = customTypeSchema.name result[key] = [ "customTypeName": customTypeName, @@ -244,11 +247,13 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } else if case .collection = field?.type{ continue } else if case .embeddedCollection(let fieldType, _) = field?.type, - case .array(let jsonArray) = value { + case .array(let jsonArray) = value + { var deserializedArray: [Any??] = [] for item in jsonArray { if case .object(let deserializedItem) = item, - case .embeddedCollection(_, .some(let customTypeSchema)) = field?.type { + case .embeddedCollection(_, .some(let customTypeSchema)) = field?.type + { let customTypeName = customTypeSchema.name deserializedArray.append([ "customTypeName": customTypeName, @@ -264,13 +269,12 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } } result[key] = deserializedArray - } - else { + } else { result[key] = extractJsonValue(key: key, value: values[key], modelSchema: modelSchema, returnTemporalType: false)! } } - return result; + return result } public func toMap( @@ -282,7 +286,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { "id": id, "modelName": modelName, "serializedData": try FlutterSerializedModel.generateSerializedData( - values: self.values, + values: values, modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, modelName: modelName @@ -292,7 +296,6 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } extension FlutterSerializedModel { - public enum CodingKeys: String, ModelKey { case id case values diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterSubscriptionEvent.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterSubscriptionEvent.swift index 5bc61602e7..85c45ef71a 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterSubscriptionEvent.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterSubscriptionEvent.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -27,14 +27,15 @@ struct FlutterSubscriptionEvent { public func toJSON(modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry, modelName: String) throws -> [String: Any] { return [ - "item": try self.item.toMap( + "item": try item.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, modelName: modelName ), - "eventType": self.eventType.rawValue + "eventType": eventType.rawValue ] - }} + } +} enum EventType: String { case create diff --git a/packages/amplify_datastore/ios/Classes/types/model/ModelSchemaError.swift b/packages/amplify_datastore/ios/Classes/types/model/ModelSchemaError.swift index f68cf3a83b..e4607a39e2 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/ModelSchemaError.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/ModelSchemaError.swift @@ -1,17 +1,17 @@ /* -* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ import Foundation diff --git a/packages/amplify_datastore/ios/Classes/types/query/QueryPaginationBuilder.swift b/packages/amplify_datastore/ios/Classes/types/query/QueryPaginationBuilder.swift index 52e569ba7c..c9af02f571 100644 --- a/packages/amplify_datastore/ios/Classes/types/query/QueryPaginationBuilder.swift +++ b/packages/amplify_datastore/ios/Classes/types/query/QueryPaginationBuilder.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -16,11 +16,10 @@ import Foundation import Amplify -public class QueryPaginationBuilder { - +public enum QueryPaginationBuilder { static func fromSerializedMap(_ serializedMap: [String: Any]?) -> QueryPaginationInput? { if let data = serializedMap { - var page: UInt = 0, limit: UInt = QueryPaginationInput.defaultLimit; + var page: UInt = 0, limit: UInt = QueryPaginationInput.defaultLimit if let pageInput = (data["page"] as? Int) { page = UInt(pageInput) } diff --git a/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift b/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift index 234d4db97e..d0b144b82b 100644 --- a/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift +++ b/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ import Flutter import Foundation import Amplify -public class QueryPredicateBuilder { +public enum QueryPredicateBuilder { static func fromSerializedMap(_ serializedMap: [String: Any]?) throws -> QueryPredicate { guard let data = serializedMap else { return QueryPredicateConstant.all @@ -26,7 +26,8 @@ public class QueryPredicateBuilder { if let queryPredicateOperationMap = data["queryPredicateOperation"] as? [String: Any] { if let fieldValue = queryPredicateOperationMap["field"] as? String, let queryFieldOperatorMap = queryPredicateOperationMap["fieldOperator"] as? [String: Any], - let operatorName = queryFieldOperatorMap["operatorName"] as? String { + let operatorName = queryFieldOperatorMap["operatorName"] as? String + { let operand = convertToAmplifyPersistable(operand: queryFieldOperatorMap["value"]) let queryField = field(fieldValue) switch operatorName { @@ -58,13 +59,13 @@ public class QueryPredicateBuilder { "Check the values that are being passed from Dart.") } } - + if let queryPredicateGroupMap = data["queryPredicateGroup"] as? [String: Any] { let serializedPredicates = queryPredicateGroupMap["predicates"] as! [[String: Any]] var predicates = try serializedPredicates.map { try fromSerializedMap($0) } var resultQueryPredicate: QueryPredicate - if(predicates[0] is QueryPredicateOperation) { - switch (queryPredicateGroupMap["type"] as! String) { + if predicates[0] is QueryPredicateOperation { + switch queryPredicateGroupMap["type"] as! String { case "and": resultQueryPredicate = (predicates[0] as! QueryPredicateOperation).and(predicates[1]) predicates = Array(predicates.dropFirst(2)) @@ -83,19 +84,19 @@ public class QueryPredicateBuilder { resultQueryPredicate = predicates[0] as! QueryPredicateGroup predicates = Array(predicates.dropFirst(1)) } - + // Now iterate over all other predicates and add - switch (queryPredicateGroupMap["type"] as! String) { + switch queryPredicateGroupMap["type"] as! String { case "and": - predicates.forEach { (predicate) in + predicates.forEach { predicate in resultQueryPredicate = (resultQueryPredicate as! QueryPredicateGroup).and(predicate) } case "or": - predicates.forEach { (predicate) in + predicates.forEach { predicate in resultQueryPredicate = (resultQueryPredicate as! QueryPredicateGroup).or(predicate) } case "not": - if(!predicates.isEmpty) { + if !predicates.isEmpty { throw DataStoreError.decodingError("Received more than one query predicates for group type not.", "Check the values that are being passed from Dart.") } @@ -109,7 +110,7 @@ public class QueryPredicateBuilder { } if let queryPredicateConstant = data["queryPredicateConstant"] as? [String: Any] { - switch (queryPredicateConstant["type"] as! String) { + switch queryPredicateConstant["type"] as! String { case "all": return QueryPredicateConstant.all default: @@ -118,11 +119,11 @@ public class QueryPredicateBuilder { "Check the values that are being passed from Dart.") } } - + throw DataStoreError.decodingError("Received invalid serialization for query predicates.", "Check the values that are being passed from Dart.") } - + static func convertToAmplifyPersistable(operand: Any?) -> Persistable? { if operand == nil { return nil diff --git a/packages/amplify_datastore/ios/Classes/types/query/QuerySortBuilder.swift b/packages/amplify_datastore/ios/Classes/types/query/QuerySortBuilder.swift index 84903b26d6..ef2544c0f3 100644 --- a/packages/amplify_datastore/ios/Classes/types/query/QuerySortBuilder.swift +++ b/packages/amplify_datastore/ios/Classes/types/query/QuerySortBuilder.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -17,14 +17,14 @@ import Foundation import Amplify import AmplifyPlugins -public class QuerySortBuilder { +public enum QuerySortBuilder { static func fromSerializedList(_ serializedList: [[String: Any]]?) throws -> [QuerySortDescriptor]? { if let serializedList = serializedList, !serializedList.isEmpty { return try serializedList.map { try fromSerializedMap($0) } } return nil } - + static func fromSerializedMap(_ serializedMap: [String: Any]) throws -> QuerySortDescriptor { if let fieldName = serializedMap["field"] as? String, let order = serializedMap["order"] as? String { switch order { diff --git a/packages/amplify_datastore/ios/Classes/types/temporal/FlutterTemporal.swift b/packages/amplify_datastore/ios/Classes/types/temporal/FlutterTemporal.swift index 701d5c6574..011383c7c8 100644 --- a/packages/amplify_datastore/ios/Classes/types/temporal/FlutterTemporal.swift +++ b/packages/amplify_datastore/ios/Classes/types/temporal/FlutterTemporal.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,16 +19,16 @@ import Foundation // Stores an ISO 8601 String to be saved to Appsync struct FlutterTemporal: TemporalSpec { - let iso8601: String init(iso8601String: String) { self.iso8601 = iso8601String self.foundationDate = Date() } + var iso8601String: String { iso8601 } - + // Not needed functions // In order to properly adhere to "TemporalSpec" these functions must be implemented // This class is solely for transmitting a ISO 8601 Date String to Appsync so these other functions are not needed @@ -37,10 +37,12 @@ struct FlutterTemporal: TemporalSpec { self.iso8601 = "" self.foundationDate = date } + static func now() -> FlutterTemporal { return FlutterTemporal(Foundation.Date()) } + func iso8601FormattedString(format: TemporalFormat, timeZone: TimeZone) -> String{ - return ""; + return "" } } From 3ad38b07526bd57d07e0b880d33f554933a72bbd Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Fri, 20 May 2022 13:07:02 -0700 Subject: [PATCH 02/10] feat(core): custom primary key supporting interface changes - Add ModelIndex ModelIdentifier interface - Make Model non-abstract class to prevent unnecessary breaking changes - Add indexes to model schema - Add query by model identifier interface --- packages/amplify_core/lib/amplify_core.dart | 2 + .../lib/src/types/models/model.dart | 36 +++++++- .../lib/src/types/models/model_index.dart | 67 ++++++++++++++ .../lib/src/types/models/model_schema.dart | 87 +++++++++---------- .../types/models/model_schema_definition.dart | 3 + .../types/query/query_field_operators.dart | 34 ++++++++ .../types/query/query_model_identifier.dart | 72 +++++++++++++++ .../lib/src/types/query/query_predicate.dart | 19 ++++ 8 files changed, 272 insertions(+), 48 deletions(-) create mode 100644 packages/amplify_core/lib/src/types/models/model_index.dart create mode 100644 packages/amplify_core/lib/src/types/query/query_model_identifier.dart diff --git a/packages/amplify_core/lib/amplify_core.dart b/packages/amplify_core/lib/amplify_core.dart index 7db97edf0e..e68980510b 100644 --- a/packages/amplify_core/lib/amplify_core.dart +++ b/packages/amplify_core/lib/amplify_core.dart @@ -52,6 +52,7 @@ export 'src/types/models/model_association.dart'; export 'src/types/models/model_field.dart'; export 'src/types/models/model_field_definition.dart'; export 'src/types/models/model_field_type.dart'; +export 'src/types/models/model_index.dart'; export 'src/types/models/model_provider.dart'; export 'src/types/models/model_schema.dart'; export 'src/types/models/model_schema_definition.dart'; @@ -66,6 +67,7 @@ export 'src/types/plugin/amplify_storage_plugin_interface.dart'; /// Query export 'src/types/query/query_field.dart'; +export 'src/types/query/query_model_identifier.dart'; /// Storage export 'src/types/storage/storage_types.dart'; diff --git a/packages/amplify_core/lib/src/types/models/model.dart b/packages/amplify_core/lib/src/types/models/model.dart index 56a75871aa..6045f9be73 100644 --- a/packages/amplify_core/lib/src/types/models/model.dart +++ b/packages/amplify_core/lib/src/types/models/model.dart @@ -19,11 +19,25 @@ import 'model_schema.dart'; import 'model_schema_definition.dart'; abstract class Model { - ModelType getInstanceType(); + ModelType getInstanceType() { + throw UnimplementedError( + 'getInstanceType() has not been implemented on Model.'); + } - String getId(); + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + String getId() { + throw UnimplementedError('getId() has not been implemented on Model.'); + } - Map toJson(); + ModelIdentifier get modelIdentifier { + throw UnimplementedError( + 'modelIdentifier has not been implemented on Model.'); + } + + Map toJson() { + throw UnimplementedError('toJson() has not been implemented on Model.'); + } const Model(); @@ -73,3 +87,19 @@ abstract class ModelType { @override int get hashCode => T.hashCode; } + +/// Model identifier presentation +abstract class ModelIdentifier { + const ModelIdentifier(); + + /// Serialize a model identifier as a map. + Map serializeAsMap(); + + /// Serialize a model identifier as a list of key-value pairs. The order of + /// key-value pairs presents primary key and sort keys. + List> serializeAsList(); + + /// Serialize a model identifier into a single string in format: + /// [#] + String serializeAsString(); +} diff --git a/packages/amplify_core/lib/src/types/models/model_index.dart b/packages/amplify_core/lib/src/types/models/model_index.dart new file mode 100644 index 0000000000..76c64a9542 --- /dev/null +++ b/packages/amplify_core/lib/src/types/models/model_index.dart @@ -0,0 +1,67 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'dart:convert'; + +import 'package:aws_common/aws_common.dart'; + +/// {@template amplify_core.models.model_index} +/// Describes an index that is created by `@primaryKey` or `@index` directive, +/// and is listed in [ModelSchemaDefinition.indexes]. +/// {@endtemplate} +class ModelIndex with AWSEquatable, AWSSerializable { + /// Index name that is defined by the name parameter of `@index` directive in + /// a model schema. This will always be null when the index is representing + /// `@primaryKey` directive. + final String? name; + + /// An array of field names. The first field is always the field that is + /// annotated by `@primaryKey` or `@index` directive , and the remaining + /// fields are the fields specified by `sortKeyFields` parameter of + /// `@primaryKey` or `@index` directive. + final List fields; + + /// {@macro model_index} + const ModelIndex({ + required this.fields, + this.name, + }); + + @override + List get props => [name, fields]; + + /// Make a copy of an existing [ModelIndex] instance. + ModelIndex copyWith({ + List? fields, + String? name, + }) => + ModelIndex(fields: fields ?? this.fields, name: name ?? this.name); + + /// Create an instance of [ModelIndex] from a json object + factory ModelIndex.fromJson(Map map) => ModelIndex( + fields: (map['fields'] as List).cast(), + name: map['name'] as String?, + ); + + /// Generate a json object that represents [ModelIndex] + @override + Map toJson() => { + 'name': name, + 'fields': fields, + }; + + @override + String toString() => 'ModelIndex(name: $name, fields: $fields)'; +} diff --git a/packages/amplify_core/lib/src/types/models/model_schema.dart b/packages/amplify_core/lib/src/types/models/model_schema.dart index 320afdf201..9a5a865268 100644 --- a/packages/amplify_core/lib/src/types/models/model_schema.dart +++ b/packages/amplify_core/lib/src/types/models/model_schema.dart @@ -17,56 +17,73 @@ library model_schema; import 'dart:convert'; +import 'package:aws_common/aws_common.dart'; import 'package:collection/collection.dart'; import 'package:meta/meta.dart'; import 'auth_rule.dart'; import 'model_field.dart'; +import 'model_index.dart'; @immutable -class ModelSchema { +class ModelSchema with AWSEquatable { final String name; - final String? pluralName; //opt - final List? authRules; //opt + final String? pluralName; + final List? authRules; final Map? fields; + final List? indexes; const ModelSchema({ required this.name, this.pluralName, this.authRules, this.fields, + this.indexes, }); - ModelSchema copyWith( - {String? name, - String? pluralName, - List? authRules, - Map? fields}) { + ModelSchema copyWith({ + String? name, + String? pluralName, + List? authRules, + Map? fields, + List? indexes, + }) { return ModelSchema( - name: name ?? this.name, - pluralName: pluralName ?? this.pluralName, - authRules: authRules ?? this.authRules, - fields: fields ?? this.fields); + name: name ?? this.name, + pluralName: pluralName ?? this.pluralName, + authRules: authRules ?? this.authRules, + fields: fields ?? this.fields, + indexes: indexes ?? this.indexes, + ); } - Map toMap() { - final map = { - 'name': name, - 'pluralName': pluralName, - 'authRules': authRules?.map((x) => x.toMap()).toList(), - 'fields': fields?.map((key, value) => MapEntry(key, value.toMap())), - }; - return Map.from(map) - ..removeWhere((k, dynamic v) => v == null); - } + @override + List get props => [ + name, + pluralName, + authRules, + fields, + indexes, + ]; + + Map toMap() => { + 'name': name, + if (pluralName != null) 'pluralName': pluralName, + if (authRules != null) + 'authRules': authRules?.map((x) => x.toMap()).toList(), + if (fields != null) + 'fields': fields?.map((key, value) => MapEntry(key, value.toMap())), + if (indexes != null) + 'indexes': indexes?.map((value) => value.toJson()).toList(), + }; factory ModelSchema.fromMap(Map map) { return ModelSchema( name: map['name'], pluralName: map['pluralName'], - authRules: List.from( - map['authRules']?.map((dynamic x) => AuthRule.fromMap(x))), + authRules: List.from(map['authRules']?.map(AuthRule.fromMap)), fields: Map.from(map['fields']), + indexes: List.from(map['indexes']), ); } @@ -77,26 +94,6 @@ class ModelSchema { @override String toString() { - return 'ModelSchema(name: $name, pluralName: $pluralName, authRules: $authRules, fields: $fields)'; - } - - @override - bool operator ==(Object other) { - if (identical(this, other)) return true; - final collectionEquals = const DeepCollectionEquality().equals; - - return other is ModelSchema && - other.name == name && - other.pluralName == pluralName && - collectionEquals(other.authRules, authRules) && - collectionEquals(other.fields, fields); - } - - @override - int get hashCode { - return name.hashCode ^ - pluralName.hashCode ^ - authRules.hashCode ^ - fields.hashCode; + return 'ModelSchema(name: $name, pluralName: $pluralName, authRules: $authRules, fields: $fields, indexes: $indexes)'; } } diff --git a/packages/amplify_core/lib/src/types/models/model_schema_definition.dart b/packages/amplify_core/lib/src/types/models/model_schema_definition.dart index cc36897801..ea1961cf6f 100644 --- a/packages/amplify_core/lib/src/types/models/model_schema_definition.dart +++ b/packages/amplify_core/lib/src/types/models/model_schema_definition.dart @@ -16,6 +16,7 @@ import 'auth_rule.dart'; import 'model_field.dart'; import 'model_field_definition.dart'; +import 'model_index.dart'; import 'model_schema.dart'; class ModelSchemaDefinition { @@ -23,6 +24,7 @@ class ModelSchemaDefinition { String? pluralName; List? authRules; late Map fields; + List? indexes; ModelSchemaDefinition() { fields = {}; @@ -38,6 +40,7 @@ class ModelSchemaDefinition { pluralName: pluralName, authRules: authRules, fields: fields, + indexes: indexes, ); } } diff --git a/packages/amplify_core/lib/src/types/query/query_field_operators.dart b/packages/amplify_core/lib/src/types/query/query_field_operators.dart index e3540f53c1..1f3ab301a4 100644 --- a/packages/amplify_core/lib/src/types/query/query_field_operators.dart +++ b/packages/amplify_core/lib/src/types/query/query_field_operators.dart @@ -72,6 +72,8 @@ abstract class QueryFieldOperator { return value.toSeconds(); } else if (isEnum(value)) { return enumToString(value); + } else if (value is ModelIdentifier) { + return value.serializeAsList(); } // TODO sanitize other types appropriately @@ -102,6 +104,22 @@ class EqualQueryOperator extends QueryFieldOperatorSingleValue { } } +class EqualModelIdentifierQueryOperator + extends QueryFieldOperatorSingleValue { + const EqualModelIdentifierQueryOperator(T value) + : super(value, QueryFieldOperatorType.equal); + + @override + bool evaluate(T? other) { + return other == value; + } + + @override + Map serializeAsMap() { + return serializeAsMapWithOperator(type.toShortString(), value); + } +} + class NotEqualQueryOperator extends QueryFieldOperatorSingleValue { const NotEqualQueryOperator(T value) : super(value, QueryFieldOperatorType.not_equal); @@ -112,6 +130,22 @@ class NotEqualQueryOperator extends QueryFieldOperatorSingleValue { } } +class NotEqualModelIdentifierQueryOperator + extends QueryFieldOperatorSingleValue { + const NotEqualModelIdentifierQueryOperator(T value) + : super(value, QueryFieldOperatorType.not_equal); + + @override + bool evaluate(T? other) { + return other != value; + } + + @override + Map serializeAsMap() { + return serializeAsMapWithOperator(type.toShortString(), value); + } +} + class LessOrEqualQueryOperator extends QueryFieldOperatorSingleValue { const LessOrEqualQueryOperator(T value) diff --git a/packages/amplify_core/lib/src/types/query/query_model_identifier.dart b/packages/amplify_core/lib/src/types/query/query_model_identifier.dart new file mode 100644 index 0000000000..a831c5832b --- /dev/null +++ b/packages/amplify_core/lib/src/types/query/query_model_identifier.dart @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:amplify_core/amplify_core.dart'; + +const dummyFieldName = 'modelIdentifier'; + +class QueryModelIdentifier { + const QueryModelIdentifier(); + + /// An **equal to** operation. + /// + /// Matches a model whose model identifier is equal to the provided value. + /// + /// ### Example: + /// The example returns Posts where the rating is equal to 10. + /// + /// ```dart + /// Amplify.DataStore.query( + /// Inventory.classType, + /// where: Inventory.MODEL_IDENTIFIER.eq( + /// InventoryModelIdentifier( + /// productID: 'product-id', + /// name: 'product-name', + /// warehouseID: 'warehouse-id', + /// region: 'some region', + /// ), + /// ), + /// ); + /// ``` + QueryByIdentifierOperation eq(T value) => QueryByIdentifierOperation( + dummyFieldName, + EqualModelIdentifierQueryOperator(value), + ); + + /// A **not equal to** operation. + /// + /// Matches a model whose model identifier is **not** equal to the provided value. + /// + /// ### Example: + /// The example returns Posts where the rating is not equal to 10. + /// + ///```dart + /// Amplify.DataStore.query( + /// Inventory.classType, + /// where: Inventory.MODEL_IDENTIFIER.ne( + /// InventoryModelIdentifier( + /// productID: 'product-id', + /// name: 'product-name', + /// warehouseID: 'warehouse-id', + /// region: 'some region', + /// ), + /// ), + /// ); + /// ``` + QueryByIdentifierOperation ne(T value) => QueryByIdentifierOperation( + dummyFieldName, + NotEqualModelIdentifierQueryOperator(value), + ); +} diff --git a/packages/amplify_core/lib/src/types/query/query_predicate.dart b/packages/amplify_core/lib/src/types/query/query_predicate.dart index 039e1b5ac9..ab11f1eb21 100644 --- a/packages/amplify_core/lib/src/types/query/query_predicate.dart +++ b/packages/amplify_core/lib/src/types/query/query_predicate.dart @@ -86,6 +86,25 @@ class QueryPredicateOperation extends QueryPredicate { } } +class QueryByIdentifierOperation extends QueryPredicate { + final String field; + final QueryFieldOperator queryFieldOperator; + + const QueryByIdentifierOperation(this.field, this.queryFieldOperator); + + @override + bool evaluate(Model model) { + return queryFieldOperator.evaluate(model.modelIdentifier); + } + + @override + Map serializeAsMap() { + return { + 'queryByIdentifierOperation': queryFieldOperator.serializeAsMap(), + }; + } +} + enum QueryPredicateGroupType { and, or, not } // Represents rating > 4 & blogName.contains("awesome") From a0f7f31001951b92f04494d58a505545bb08def7 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Fri, 20 May 2022 16:22:09 -0700 Subject: [PATCH 03/10] feat(datastore): custom primary key Flutter native implementation --- .../AmplifyDataStorePlugin.kt | 8 +- .../FlutterSubscriptionDataProcessedEvent.kt | 1 - .../types/hub/FlutterSyncMetaData.kt | 3 +- .../types/model/FlutterModelIndex.kt | 38 ++++ .../types/model/FlutterModelSchema.kt | 56 ++++-- .../types/model/FlutterSerializedModel.kt | 2 - .../types/query/QueryPredicateBuilder.kt | 96 +++++++++- .../example/ios/Runner/Info.plist | 2 + .../ios/Classes/FlutterSchemaRegistry.swift | 5 +- .../ios/Classes/GetJsonValue.swift | 28 --- .../Classes/SwiftAmplifyDataStorePlugin.swift | 21 +- .../types/model/FlutterModelAttribute.swift | 31 +++ .../types/model/FlutterModelSchema.swift | 66 +++++-- .../types/model/FlutterSerializedModel.swift | 180 +++++++++++------- .../types/query/QueryPredicateBuilder.swift | 84 ++++++-- .../ios/Classes/utils/modelHelpers.swift | 64 +++++++ 16 files changed, 517 insertions(+), 168 deletions(-) create mode 100644 packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelIndex.kt delete mode 100644 packages/amplify_datastore/ios/Classes/GetJsonValue.swift create mode 100644 packages/amplify_datastore/ios/Classes/types/model/FlutterModelAttribute.swift create mode 100644 packages/amplify_datastore/ios/Classes/utils/modelHelpers.swift diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt index c4f9b21e04..40da63aa38 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePlugin.kt @@ -301,8 +301,8 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { val plugin = Amplify.DataStore.getPlugin("awsDataStorePlugin") as AWSDataStorePlugin val instance = SerializedModel.builder() - .serializedData(serializedModelData) .modelSchema(schema) + .serializedData(serializedModelData) .build() plugin.delete( @@ -357,8 +357,8 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { val plugin = Amplify.DataStore.getPlugin("awsDataStorePlugin") as AWSDataStorePlugin val serializedModel = SerializedModel.builder() - .serializedData(serializedModelData) .modelSchema(schema) + .serializedData(serializedModelData) .build() plugin.save( @@ -569,8 +569,8 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { // ignore field if the field doesn't have valid schema in ModelProvider val fieldModelSchema = modelProvider.modelSchemas()[field.targetType] ?: continue result[key] = SerializedModel.builder() - .serializedData(deserializeNestedModel(fieldSerializedData as Map, fieldModelSchema)) .modelSchema(fieldModelSchema) + .serializedData(deserializeNestedModel(fieldSerializedData as Map, fieldModelSchema)) .build() } else if (field.isCustomType) { // ignore field if the field doesn't have valid schema in ModelProvider @@ -739,8 +739,8 @@ class AmplifyDataStorePlugin : FlutterPlugin, MethodCallHandler { ResolutionStrategy.RETRY_LOCAL -> onDecision.accept(DataStoreConflictHandler.ConflictResolutionDecision.retryLocal()) ResolutionStrategy.RETRY -> { val serializedModel = SerializedModel.builder() - .serializedData((resultMap["customModel"] as Map<*, *>).cast()) .modelSchema(modelProvider.modelSchemas().getValue(modelName)) + .serializedData((resultMap["customModel"] as Map<*, *>).cast()) .build() onDecision.accept( DataStoreConflictHandler.ConflictResolutionDecision.retry( diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSubscriptionDataProcessedEvent.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSubscriptionDataProcessedEvent.kt index 11258bfb71..d1e1bb5eea 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSubscriptionDataProcessedEvent.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSubscriptionDataProcessedEvent.kt @@ -30,7 +30,6 @@ class FlutterSubscriptionDataProcessedEvent( "modelName" to model.modelName, "element" to mapOf( "syncMetadata" to mapOf( - "id" to syncMetadata.id, "_deleted" to syncMetadata.isDeleted, "_version" to syncMetadata.version, "_lastChangedAt" to syncMetadata.lastChangedAt?.secondsSinceEpoch diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt index e26d117306..c8512e6d94 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/hub/FlutterSyncMetaData.kt @@ -21,10 +21,9 @@ import com.amplifyframework.datastore.syncengine.OutboxMutationEvent class FlutterSyncMetaData(private var metadata: OutboxMutationEvent.OutboxMutationEventElement) { fun toValueMap(): Map { return mapOf( - "id" to this.metadata.model.id, "_deleted" to this.metadata.isDeleted, "_version" to this.metadata.version, - "_lastChangedAt" to (this.metadata.lastChangedAt ?: null) + "_lastChangedAt" to this.metadata.lastChangedAt ) } } diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelIndex.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelIndex.kt new file mode 100644 index 0000000000..332a2f8c94 --- /dev/null +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelIndex.kt @@ -0,0 +1,38 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +package com.amazonaws.amplify.amplify_datastore.types.model + +import com.amazonaws.amplify.amplify_core.cast +import com.amplifyframework.core.model.ModelIndex + +data class FlutterModelIndex(val map: Map) { + val name: String = map["name"] as String? ?: unnamedIndexKey + val fields: List = when (val fields = map["fields"]) { + is List<*> -> fields.cast() + else -> emptyList() + } + + fun convertToNativeModelIndex(): ModelIndex { + return ModelIndex.builder() + .indexName(name) + .indexFieldNames(fields) + .build() + } + + companion object { + const val unnamedIndexKey = "undefined" + } +} diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt index cb71c20207..a113bb9ab9 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt @@ -1,5 +1,5 @@ /* - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -15,35 +15,57 @@ package com.amazonaws.amplify.amplify_datastore.types.model +import com.amazonaws.amplify.amplify_core.cast +import com.amplifyframework.core.model.Model +import com.amplifyframework.core.model.ModelIndex import com.amplifyframework.core.model.ModelSchema import com.amplifyframework.core.model.SerializedModel data class FlutterModelSchema(val map: Map) { val name: String = map["name"] as String private val pluralName: String? = map["pluralName"] as String? - private val authRules: List? = - (map["authRules"] as List>?)?.map { FlutterAuthRule(it) } - private val fields: Map = - (map["fields"] as Map).mapValues { FlutterModelField(it.value as Map) } + private val authRules: List = when (val rawAuthRules = map["authRules"]) { + is List<*> -> (rawAuthRules.cast>()).map { FlutterAuthRule(it) } + else -> emptyList() + } + private val fields: Map = when (val rawFields = map["fields"]) { + is Map<*, *> -> (rawFields.cast>()).mapValues { FlutterModelField(it.value) } + else -> emptyMap() + } private val associations: Map = fields.filterKeys { key -> fields[key]?.getModelAssociation() != null } .mapValues { it.value.getModelAssociation()!! } + // In amplify-android, primaryKey and indexes are categories as ModelIndex + private val indexes: Map = run { + val parsedIndexes = emptyMap().toMutableMap() + val rawIndexes = map["indexes"] + + if (rawIndexes is List<*>) { + parsedIndexes.putAll( + (rawIndexes.cast>()).associate { + (it["name"] as String? + ?: FlutterModelIndex.unnamedIndexKey) to FlutterModelIndex(it).convertToNativeModelIndex() + }.toMap() + ) + } + + parsedIndexes + } + fun convertToNativeModelSchema(): ModelSchema { - var builder: ModelSchema.Builder = ModelSchema.builder() + return ModelSchema.builder() .name(name) .pluralName(pluralName) .fields(fields.mapValues { it.value.convertToNativeModelField() }) - - if (!authRules.isNullOrEmpty()) { - builder = builder.authRules(authRules.map { it.convertToNativeAuthRule() }) - } - if (!associations.isEmpty()) { - builder = builder.associations( - associations.mapValues { it.value.convertToNativeModelAssociation() } - ) - } - builder.modelClass(SerializedModel::class.java) - return builder.build() + .indexes(indexes) + .authRules(authRules.map { it.convertToNativeAuthRule() }) + .associations(associations.mapValues { it.value.convertToNativeModelAssociation() }) + .modelClass(SerializedModel::class.java) + .modelType(Model.Type.USER) + // to allow amplify-android correctly interpret custom primary key + // schema version needs to be >= 1 + .version(1) + .build(); } } diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt index 097d4d8f23..5fb9d24a98 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterSerializedModel.kt @@ -30,7 +30,6 @@ data class FlutterSerializedModel(val serializedModel: SerializedModel) { ) // ignored fields - private val id: String = serializedModel.id private val modelName: String = parseModelName(serializedModel.modelName) // ModelSchema -> SerializedModel should always have a name @@ -39,7 +38,6 @@ data class FlutterSerializedModel(val serializedModel: SerializedModel) { val cleanedSerializedData: Map = serializedData.filterValues { it != null } return mapOf( - "id" to id, "serializedData" to cleanedSerializedData, "modelName" to modelName ) diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt index fc460c86d5..ae31826d02 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilder.kt @@ -15,8 +15,10 @@ package com.amazonaws.amplify.amplify_datastore.types.query +import com.amazonaws.amplify.amplify_core.cast import com.amazonaws.amplify.amplify_datastore.util.safeCastToList import com.amazonaws.amplify.amplify_datastore.util.safeCastToMap +import com.amplifyframework.core.model.ModelIdentifier import com.amplifyframework.core.model.ModelSchema import com.amplifyframework.core.model.annotations.BelongsTo import com.amplifyframework.core.model.query.predicate.QueryField @@ -25,6 +27,7 @@ import com.amplifyframework.core.model.query.predicate.QueryPredicateGroup import com.amplifyframework.core.model.query.predicate.QueryPredicateOperation import com.amplifyframework.core.model.query.predicate.QueryPredicateOperation.not import com.amplifyframework.core.model.query.predicate.QueryPredicates +import java.io.Serializable class QueryPredicateBuilder { companion object { @@ -46,7 +49,12 @@ class QueryPredicateBuilder { val association = modelSchema.associations.getValue(field) if (BelongsTo::class.java.simpleName.equals(association.name)) { - field = modelSchema.associations.getValue(field).targetName + field = when (val targetNames = modelSchema.associations.getValue(field).targetNames) { + // if the belongs to parent model has custom primary key + // the query field should be this special one + is Array<*> -> if (targetNames.size > 1) "@@" + field + "ForeignKey" else targetNames[0] + else -> modelSchema.associations.getValue(field).targetName + } } } @@ -55,8 +63,26 @@ class QueryPredicateBuilder { queryPredicateOperationMap["fieldOperator"].safeCastToMap()!! val operand: Any? = queryFieldOperatorMap["value"] when (queryFieldOperatorMap["operatorName"]) { - "equal" -> return queryField.eq(operand) - "not_equal" -> return queryField.ne(operand) + "equal" -> return when (operand) { + is List<*> -> { + convertQueryByNestedModelIdentifierToPredicate( + queryField, + operand.cast>(), + true + ) + } + else -> queryField.eq(operand) + } + "not_equal" -> return when (operand) { + is List<*> -> { + convertQueryByNestedModelIdentifierToPredicate( + queryField, + operand.cast>(), + false + ) + } + else -> queryField.ne(operand) + } "less_or_equal" -> return queryField.le(operand as Comparable?) "less_than" -> return queryField.lt(operand as Comparable?) "greater_or_equal" -> return queryField.ge(operand as Comparable?) @@ -137,6 +163,26 @@ class QueryPredicateBuilder { } } + if (serializedMap.containsKey("queryByIdentifierOperation")) { + val queryByIdentifierOperation: Map = + serializedMap["queryByIdentifierOperation"].safeCastToMap()!! + val operands = queryByIdentifierOperation["value"] + + if (operands !is List<*>) { + throw IllegalArgumentException( + "A queryByIdentifierOperation must provide a list of operands" + ) + } + + return when (queryByIdentifierOperation["operatorName"]) { + "equal" -> convertQueryByIdentifierOperationToPredicate(operands.cast(), true) + "not_equal" -> convertQueryByIdentifierOperationToPredicate(operands.cast(), false) + else -> throw IllegalArgumentException( + "Operator cannot be equal for a queryByIdentifierOperation" + ) + } + } + return null } @@ -144,5 +190,49 @@ class QueryPredicateBuilder { fun fromSerializedMap(serializedMap: Map?): QueryPredicate? { return fromSerializedMap(serializedMap, null) } + + @JvmStatic + fun convertQueryByIdentifierOperationToPredicate(operands: List>, isEqualOperator: Boolean): + QueryPredicate { + var predicates = operands.map { + val operandEntry = it.entries.first() + when { + isEqualOperator -> QueryField.field(operandEntry.key).eq(operandEntry.value) + else -> QueryField.field(operandEntry.key).ne(operandEntry.value) + } + } + + if (predicates.size == 1) { + return predicates[0] + } + + var predicateGroup: QueryPredicateGroup = predicates[0].and(predicates[1]) + predicates = predicates.drop(2) + + predicates.forEach { predicate -> + predicateGroup = predicateGroup.and(predicate) + } + + return predicateGroup + } + + @JvmStatic + fun convertQueryByNestedModelIdentifierToPredicate( + queryField: QueryField, operands: List>, + isEqualOperator: Boolean + ): QueryPredicate { + val identifierFieldsValues = operands.map { it.values.first() } + val identifier = ModelIdentifier.Helper.getIdentifier( + identifierFieldsValues[0], + identifierFieldsValues + .subList(1, identifierFieldsValues.size) + ) + + if (isEqualOperator) { + return queryField.eq(identifier) + } + + return queryField.ne(identifier) + } } } diff --git a/packages/amplify_datastore/example/ios/Runner/Info.plist b/packages/amplify_datastore/example/ios/Runner/Info.plist index 1b82362f20..c7e7def85b 100644 --- a/packages/amplify_datastore/example/ios/Runner/Info.plist +++ b/packages/amplify_datastore/example/ios/Runner/Info.plist @@ -41,5 +41,7 @@ UIViewControllerBasedStatusBarAppearance + CADisableMinimumFrameDurationOnPhone + diff --git a/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift b/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift index 0ff8dd8dd3..24dbe32bb9 100644 --- a/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift +++ b/packages/amplify_datastore/ios/Classes/FlutterSchemaRegistry.swift @@ -51,10 +51,9 @@ public final class FlutterSchemaRegistry: AmplifyModelRegistration { jsonObj = obj } // the json string presents an object - if let jsonObj = jsonObj, - case .string(let id) = jsonObj["id"] + if let jsonObj = jsonObj { - let model = FlutterSerializedModel(id: id, map: jsonObj) + let model = FlutterSerializedModel(map: jsonObj, modelName: entry.value.name) return model } throw DataStoreError.decodingError( diff --git a/packages/amplify_datastore/ios/Classes/GetJsonValue.swift b/packages/amplify_datastore/ios/Classes/GetJsonValue.swift deleted file mode 100644 index 48a3447b59..0000000000 --- a/packages/amplify_datastore/ios/Classes/GetJsonValue.swift +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -import Amplify - -func getJSONValue(_ jsonDict: [String: Any]) throws -> [String: JSONValue] { - guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict) else { - throw DataStoreError.decodingError("Unable to deserialize json data", "Check the model structure.") - } - guard let jsonValue = try? JSONDecoder().decode([String: JSONValue].self, - from: jsonData) - else { - throw DataStoreError.decodingError("Unable to decode json value", "Check the model structure.") - } - return jsonValue -} diff --git a/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift b/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift index fa9ae0c57e..7949e108b4 100644 --- a/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift +++ b/packages/amplify_datastore/ios/Classes/SwiftAmplifyDataStorePlugin.swift @@ -156,8 +156,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { customTypeSchemaRegistry: customTypeSchemaRegistry ) - var errorHandler: DataStoreErrorHandler = createErrorHandler(args: args) - var conflictHandler: DataStoreConflictHandler = createConflictHandler(args: args) + let errorHandler: DataStoreErrorHandler = createErrorHandler(args: args) + let conflictHandler: DataStoreConflictHandler = createConflictHandler(args: args) let dataStorePlugin = AWSDataStorePlugin(modelRegistration: modelSchemaRegistry, configuration: .custom( @@ -215,14 +215,14 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { modelSchemaRegistry: modelSchemaRegistry, modelName: modelName ) - let queryPredicates = try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String: Any]) + let queryPredicates = try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String : Any]) let querySortInput = try QuerySortBuilder.fromSerializedList(args["querySort"] as? [[String: Any]]) let queryPagination = QueryPaginationBuilder.fromSerializedMap(args["queryPagination"] as? [String: Any]) try bridge.onQuery(FlutterSerializedModel.self, modelSchema: modelSchema, where: queryPredicates, sort: querySortInput, - paginate: queryPagination) { result in + paginate: queryPagination) { (result) in switch result { case .failure(let error): print("Query API failed. Error = \(error)") @@ -230,7 +230,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { flutterResult: flutterResult) case .success(let res): do { - let serializedResults = try res.map { queryResult -> [String: Any] in + let serializedResults = try res.map { (queryResult) -> [String: Any] in return try queryResult.toMap( modelSchemaRegistry: modelSchemaRegistry, customTypeSchemaRegistry: customTypeSchemaRegistry, @@ -286,9 +286,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { let queryPredicates = filterQueryPredicateAll(queryPredicates: try QueryPredicateBuilder.fromSerializedMap(args["queryPredicate"] as? [String: Any])) let serializedModelData = try FlutterDataStoreRequestUtils.getSerializedModelData(methodChannelArguments: args) - let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: serializedModelData) - let serializedModel = FlutterSerializedModel(id: modelID, map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData)) + let serializedModel = FlutterSerializedModel(map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData), modelName: modelSchema.name) try bridge.onSave( serializedModel: serializedModel, @@ -329,9 +328,8 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { let queryPredicates = queryPredicatesMap != nil ? try QueryPredicateBuilder.fromSerializedMap(queryPredicatesMap) : nil let serializedModelData = try FlutterDataStoreRequestUtils.getSerializedModelData(methodChannelArguments: args) - let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: serializedModelData) - let serializedModel = FlutterSerializedModel(id: modelID, map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData)) + let serializedModel = FlutterSerializedModel(map: try FlutterDataStoreRequestUtils.getJSONValue(serializedModelData), modelName: modelSchema.name) try bridge.onDelete( serializedModel: serializedModel, @@ -508,7 +506,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { "This should not happen, please open an issue at https://github.com/aws-amplify/amplify-flutter/issues" ) } - let schema: ModelSchema = try FlutterModelSchema.init(serializedData: serializedSchema) + let schema: ModelSchema = try FlutterModelSchema.init(serializedData: serializedSchema, isModelType: false) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemaRegistry) customTypeSchemaRegistry.addModelSchema(modelName: schemaName, modelSchema: schema) } @@ -686,8 +684,7 @@ public class SwiftAmplifyDataStorePlugin: NSObject, FlutterPlugin { else { throw DataStoreError.decodingError("Flutter CustomModel map is invalid", "Check the values that are being passed from Dart.") } - let modelID = try FlutterDataStoreRequestUtils.getModelID(serializedModelData: modelMap) - let serializedModel = try FlutterSerializedModel(id: modelID, map: FlutterDataStoreRequestUtils.getJSONValue(modelMap)) + let serializedModel = try FlutterSerializedModel(map: FlutterDataStoreRequestUtils.getJSONValue(modelMap), modelName: modelName) onDecision(.retry(serializedModel)) default: print("Unrecognized resolutionStrategy to resolve conflict. Applying default conflict resolution, applyRemote.") diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAttribute.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAttribute.swift new file mode 100644 index 0000000000..2443c00405 --- /dev/null +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAttribute.swift @@ -0,0 +1,31 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import Foundation +import Amplify + +public enum FlutterModelAttribute { + case index(fields: [String], name: String?) + case primaryKey(fields: [String]) + + func convertToNativeModelAttribute() -> ModelAttribute { + switch self { + case let .index(fields, name): + return .index(fields: fields, name: name) + case let .primaryKey(fields): + return .primaryKey(fields: fields) + } + } +} diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift index af1accc9be..949b37f365 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelSchema.swift @@ -21,12 +21,11 @@ struct FlutterModelSchema { let name: String let fields: [String: FlutterModelField] let pluralName: String? - let authRules: [FlutterAuthRule]? + let authRules: [FlutterAuthRule] + var primaryKeyFieldKeys = [ModelFieldName]() + var attributes = [FlutterModelAttribute]() - // Not used for now - let attributes: [ModelAttribute] = [] - - init(serializedData: [String: Any]) throws { + init(serializedData: [String: Any], isModelType: Bool = true) throws { guard let name = serializedData["name"] as? String else { throw ModelSchemaError.parse( className: "FlutterModelSchema", @@ -48,11 +47,41 @@ struct FlutterModelSchema { self.pluralName = serializedData["pluralName"] as? String if let inputAuthRulesMap = serializedData["authRules"] as? [[String: Any]] { - self.authRules = try inputAuthRulesMap.map { + authRules = try inputAuthRulesMap.map { try FlutterAuthRule(serializedData: $0) } } else { - self.authRules = nil + authRules = [FlutterAuthRule]() + } + + if let inputIndexes = serializedData["indexes"] as? [[String: Any]] { + for inputIndex in inputIndexes { + let parsedIndex = try parseInputIndexes(serializedData: inputIndex) + // When a model index is without a name, this model index is used as + // the primary key of the model + if (parsedIndex.name == nil) { + primaryKeyFieldKeys += parsedIndex.fields + // When the model index is a primary key and it has only 1 field + // it doesn't need to create a db index for it + // e.g. using @primaryKey directive on a model field + if (parsedIndex.fields.count == 1) { + continue + } + } + + attributes.append( + FlutterModelAttribute.index(fields: parsedIndex.fields, name: parsedIndex.name) + ) + } + } + + // After parsing model index, if primaryKeyFieldKeys is still empty then + // 1. The model doesn't use custom primary key + // 2. The model doesn't have a explicit id field + // 3. Model generated prior to custom primary key feature + // Add the default id field as the primary key + if (primaryKeyFieldKeys.isEmpty && isModelType) { + primaryKeyFieldKeys += ["id"] } } @@ -60,11 +89,24 @@ struct FlutterModelSchema { return ModelSchema.init( name: name, pluralName: pluralName, - authRules: authRules?.map{ - $0.convertToNativeAuthRule() - } ?? [AuthRule](), - attributes: attributes, - fields: try fields.mapValues { try $0.convertToNativeModelField(customTypeSchemasRegistry: customTypeSchemasRegistry) } + authRules: authRules.map{ $0.convertToNativeAuthRule() }, + attributes: attributes.map{ $0.convertToNativeModelAttribute() }, + fields: try fields.mapValues { + try $0.convertToNativeModelField(customTypeSchemasRegistry: customTypeSchemasRegistry) + }, + primaryKeyFieldKeys: primaryKeyFieldKeys ) } + + private func parseInputIndexes(serializedData: [String: Any]) throws -> (fields: [String], name: String?) { + let name = serializedData["name"] as? String + guard let fields = serializedData["fields"] as? [String] else { + throw ModelSchemaError.parse( + className: "FlutterModelIndex", + fieldName: "name", + desiredType: "[String]") + } + + return (fields, name) + } } diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift index c69b1a0652..87028d2fca 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift @@ -17,24 +17,39 @@ import Flutter import Foundation import Amplify -struct FlutterSerializedModel: Model, JSONValueHolder { - public let id: String +public struct FlutterSerializedModel: Model, ModelIdentifiable, JSONValueHolder { + public typealias IdentifierFormat = ModelIdentifierFormat.Custom + public typealias Identifier = ModelIdentifier public var values: [String: JSONValue] + var _modelName: String - public init(id: String = UUID().uuidString, map: [String: JSONValue]) { - self.id = id + public var modelName: String { + _modelName + } + + public init(map: [String: JSONValue], modelName: String) { self.values = map + self._modelName = modelName } public init(from decoder: Decoder) throws { - let y = try decoder.container(keyedBy: CodingKeys.self) - self.id = try y.decode(String.self, forKey: .id) - let json = try JSONValue(from: decoder) let typeName = json["__typename"] let modified = FlutterSerializedModel.removeReservedNames(json) + self._modelName = try { () -> String in + switch typeName { + case .some(.string(let deserializedValue)): + return deserializedValue + default: + throw DataStoreError.decodingError( + "__typename was missing decoding JSON payload to FlutterSerializedModel", + "please open an issue at https://github.com/aws-amplify/amplify-flutter/issues" + ) + } + }() + if case .object(var v) = modified { v["__typename"] = typeName values = v @@ -72,11 +87,11 @@ struct FlutterSerializedModel: Model, JSONValueHolder { try x.encode(values) } - internal func jsonValue(for key: String) -> Any?? { + public func jsonValue(for key: String) -> Any?? { return FlutterSerializedModel.extractJsonValue(value: values[key]) } - internal func jsonValue(for key: String, modelSchema: ModelSchema) -> Any?? { + public func jsonValue(for key: String, modelSchema: ModelSchema) -> Any?? { return FlutterSerializedModel.extractJsonValue(key: key, value: values[key], modelSchema: modelSchema) } @@ -101,25 +116,25 @@ struct FlutterSerializedModel: Model, JSONValueHolder { private static func extractJsonValue(key: String, value: JSONValue?, modelSchema: ModelSchema, returnTemporalType: Bool = true) -> Any?? { let field = modelSchema.field(withName: key) - switch (field?.type, value) { - case (.int, .number(let deserializedValue)): - return Int(deserializedValue) - case (.dateTime, .string(let deserializedValue)), (.date, .string(let deserializedValue)), (.time, .string(let deserializedValue)): - - // If returning value for Amplify iOS library return FlutterTemporal - if returnTemporalType { - return FlutterTemporal(iso8601String: deserializedValue) - } - // Else returning value to be serialized to Flutter layer - else{ - return deserializedValue - } + switch (field?.type, value) { + case (.int, .number(let deserializedValue)): + return Int(deserializedValue) + case (.dateTime, .string(let deserializedValue)), (.date, .string(let deserializedValue)), (.time, .string(let deserializedValue)): - case (.timestamp, .number(let deserializedValue)): - return Int(deserializedValue) - default: - return extractJsonValue(value: value) + // If returning value for Amplify iOS library return FlutterTemporal + if returnTemporalType { + return FlutterTemporal(iso8601String: deserializedValue) + } + // Else returning value to be serialized to Flutter layer + else{ + return deserializedValue } + + case (.timestamp, .number(let deserializedValue)): + return Int(deserializedValue) + default: + return extractJsonValue(value: value) + } } private static func deserializeValue(value: JSONValue?, fieldType: Codable.Type) -> Any?? { @@ -209,41 +224,49 @@ struct FlutterSerializedModel: Model, JSONValueHolder { continue } - if case .object(let deserializedValue) = value { - // If a field that has many models - if deserializedValue["associatedField"] != nil && deserializedValue["associatedId"] != nil { - result[key] = nil - } - // If a field that has one or belongs to a model - else if case .string(let modelId) = deserializedValue["id"], - case .model(let nextModelName) = field!.type - { - result[key] = [ - "id": modelId, - "modelName": nextModelName, - "serializedData": try generateSerializedData( - values: deserializedValue, - modelSchemaRegistry: modelSchemaRegistry, - customTypeSchemaRegistry: customTypeSchemaRegistry, - modelName: nextModelName - ) - ] - } - // if a field has a single CustomType value presented as JSONValue.object - else if case .embedded(_, .some(let customTypeSchema)) = field?.type, - case .some(.object(let deserializedValue)) = values[key] - { - let customTypeName = customTypeSchema.name - result[key] = [ - "customTypeName": customTypeName, - "serializedData": try FlutterSerializedModel.generateSerializedData( - values: deserializedValue, - modelSchemaRegistry: modelSchemaRegistry, - customTypeSchemaRegistry: customTypeSchemaRegistry, - modelName: customTypeName - ) - ] - } + if case let .object(deserializedValue) = value { + // If a field that has many models + if deserializedValue["associatedField"] != nil && deserializedValue["associatedId"] != nil { + result[key] = nil + } + // If a field that has one or belongs to a model + else if case .model(let nextModelName) = field!.type { + let attachNestedModel = try FlutterSerializedModel.hasValidNestedModelData( + modelName: nextModelName, + nestedModelData: deserializedValue, + modelSchemaRegistry: modelSchemaRegistry, + customTypeSchemaRegistry: customTypeSchemaRegistry + ) + + if !attachNestedModel { + continue + } + + result[key] = [ + "modelName": nextModelName, + "serializedData": try generateSerializedData( + values: deserializedValue, + modelSchemaRegistry: modelSchemaRegistry, + customTypeSchemaRegistry: customTypeSchemaRegistry, + modelName: nextModelName + ) + ] + } + // if a field has a single CustomType value presented as JSONValue.object + else if case .embedded(_, .some(let customTypeSchema)) = field?.type, + case .some(.object(let deserializedValue)) = values[key] + { + let customTypeName = customTypeSchema.name + result[key] = [ + "customTypeName": customTypeName, + "serializedData": try FlutterSerializedModel.generateSerializedData( + values: deserializedValue, + modelSchemaRegistry: modelSchemaRegistry, + customTypeSchemaRegistry: customTypeSchemaRegistry, + modelName: customTypeName + ) + ] + } } else if case .collection = field?.type{ continue } else if case .embeddedCollection(let fieldType, _) = field?.type, @@ -277,13 +300,39 @@ struct FlutterSerializedModel: Model, JSONValueHolder { return result } + private static func hasValidNestedModelData( + modelName: String, + nestedModelData: [String: JSONValue?], + modelSchemaRegistry: FlutterSchemaRegistry, + customTypeSchemaRegistry: FlutterSchemaRegistry + ) throws -> Bool { + let modelSchema = try FlutterSerializedModel.getSchema( + modelSchemaRegistry: modelSchemaRegistry, + customTypeSchemaRegistry: customTypeSchemaRegistry, + modelName: modelName + ) + + return modelSchema.primaryKey.fields + .map { $0.name } + .allSatisfy { + guard let value = nestedModelData[$0] else { + return false + } + + if case .null = value { + return false + } + + return true + } + } + public func toMap( modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry, modelName: String ) throws -> [String: Any] { return [ - "id": id, "modelName": modelName, "serializedData": try FlutterSerializedModel.generateSerializedData( values: values, @@ -295,11 +344,10 @@ struct FlutterSerializedModel: Model, JSONValueHolder { } } -extension FlutterSerializedModel { - public enum CodingKeys: String, ModelKey { - case id +public extension FlutterSerializedModel { + enum CodingKeys: String, ModelKey { case values } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self } diff --git a/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift b/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift index d0b144b82b..20e6295d4e 100644 --- a/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift +++ b/packages/amplify_datastore/ios/Classes/types/query/QueryPredicateBuilder.swift @@ -28,12 +28,28 @@ public enum QueryPredicateBuilder { let queryFieldOperatorMap = queryPredicateOperationMap["fieldOperator"] as? [String: Any], let operatorName = queryFieldOperatorMap["operatorName"] as? String { - let operand = convertToAmplifyPersistable(operand: queryFieldOperatorMap["value"]) + let operand = convertToAmplifyPersistable(value: queryFieldOperatorMap["value"]) let queryField = field(fieldValue) switch operatorName { case "equal": + if operand == nil, + let operands = queryFieldOperatorMap["value"] as? [[String: Any]] { + return try convertIdentifierFieldOperatorToPredicate( + operands: operands, + field: queryField, + isEqualOperator: true + ) + } return queryField.eq(operand) case "not_equal": + if operand == nil, + let operands = queryFieldOperatorMap["value"] as? [[String: Any]] { + return try convertIdentifierFieldOperatorToPredicate( + operands: operands, + field: queryField, + isEqualOperator: false + ) + } return queryField.ne(operand) case "less_or_equal": return queryField.le(operand!) @@ -46,8 +62,8 @@ public enum QueryPredicateBuilder { case "contains": return queryField.contains(operand as! String) case "between": - return queryField.between(start: convertToAmplifyPersistable(operand: queryFieldOperatorMap["start"])!, - end: convertToAmplifyPersistable(operand: queryFieldOperatorMap["end"])!) + return queryField.between(start: convertToAmplifyPersistable(value: queryFieldOperatorMap["start"])!, + end: convertToAmplifyPersistable(value: queryFieldOperatorMap["end"])!) case "begins_with": return queryField.beginsWith(operand as! String) default: @@ -120,26 +136,58 @@ public enum QueryPredicateBuilder { } } + if let queryByIdentifierOperationMap = data["queryByIdentifierOperation"] as? [String: Any] { + let operatorName = queryByIdentifierOperationMap["operatorName"] as? String + guard let operands = queryByIdentifierOperationMap["value"] as? [[String: Any]] else { + throw DataStoreError.decodingError("A queryByIdentifierOperation must provide a list of operands. ", + "Check the values that are being passed from Dart.") + } + + switch(operatorName) { + case "equal": + return try convertIdentifierOperatorToPredicateGroup(operands: operands, isEqualOpeartor: true) + case "not_equal": + return try convertIdentifierOperatorToPredicateGroup(operands: operands, isEqualOpeartor: false) + default: + throw DataStoreError.decodingError("Received invalid serialized query by identifier operation. ", + "Check the values that are being passed from Dart.") + } + } + throw DataStoreError.decodingError("Received invalid serialization for query predicates.", "Check the values that are being passed from Dart.") } - static func convertToAmplifyPersistable(operand: Any?) -> Persistable? { - if operand == nil { - return nil + static func convertIdentifierFieldOperatorToPredicate(operands: [[String: Any]], field: QueryField, isEqualOperator: Bool) throws -> QueryPredicate { + let identifierFields = try convertToModelIdentifierFields(values: operands) + let operand = FlutterSerializedModel.Identifier.make(fields: identifierFields).stringValue + + return isEqualOperator ? field.eq(operand) : field.ne(operand) + } + + static func convertIdentifierOperatorToPredicateGroup(operands: [[String: Any]], isEqualOpeartor: Bool) throws -> QueryPredicate { + let identifierFields = try convertToModelIdentifierFields(values: operands) + var predicates: [QueryPredicate] = identifierFields.map { + let queryFiled = field($0.name) + let value = convertToAmplifyPersistable(value: $0.value) + if (isEqualOpeartor) { + return queryFiled.eq(value) + } + + return queryFiled.ne(value) } - switch operand { - case is Int: - return operand as! Int - case is Double: - return operand as! Double - case is Bool: - return operand as! Bool - case is String: - return operand as! String - default: - // TODO: This should probably be an error case - return operand as? Persistable + + if (predicates.count == 1) { + return predicates[0] } + + var predicateGroup = (predicates[0] as! QueryPredicateOperation).and(predicates[1]) + predicates = Array(predicates.dropFirst(2)) + + predicates.forEach { + predicateGroup = predicateGroup.and($0) + } + + return predicateGroup } } diff --git a/packages/amplify_datastore/ios/Classes/utils/modelHelpers.swift b/packages/amplify_datastore/ios/Classes/utils/modelHelpers.swift new file mode 100644 index 0000000000..c970bc4ca6 --- /dev/null +++ b/packages/amplify_datastore/ios/Classes/utils/modelHelpers.swift @@ -0,0 +1,64 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import Foundation +import Amplify + +public func convertToAmplifyPersistable(value: Any?) -> Persistable? { + if value == nil { + return nil + } + switch value { + case is Int: + return value as? Int + case is Double: + return value as? Double + case is Bool: + return value as? Bool + case is String: + return value as? String + default: + // TODO: This should probably be an error case + return value as? Persistable + } +} + +public func convertToModelIdentifierFields(values: [[String: Any]]) throws -> [ModelIdentifierProtocol.Field] { + if (values.isEmpty) { + throw DataStoreError.decodingError("Model identifier should contain at least 1 field.", "Check the serialized model.") + } + + return try values.map { + guard + let fieldName = $0.keys.first, + let fieldValue = convertToAmplifyPersistable(value: $0.values.first) else { + throw DataStoreError.decodingError("Model indentifier should contain 1 key-value pair.", "Check the serialized model.") + } + + return (name: fieldName, value: fieldValue) + } +} + +public func getJSONValue(_ jsonDict: [String: Any]) throws -> [String: JSONValue] { + guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict) else { + throw DataStoreError.decodingError("Unable to deserialize json data", "Check the model structure.") + } + guard let jsonValue = try? JSONDecoder().decode([String: JSONValue].self, + from: jsonData) + else { + throw DataStoreError.decodingError("Unable to decode json value", "Check the model structure.") + } + return jsonValue +} From 3ade49463a3b88ee149c52e78e8cbac43fb81975 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 25 May 2022 11:23:23 -0700 Subject: [PATCH 04/10] chore(datastore): unit tests for custom primary key in Flutter --- .../test/amplify_datastore_clear_test.dart | 2 +- ...y_datastore_custom_error_handler_test.dart | 2 +- .../test/amplify_datastore_delete_test.dart | 2 +- .../test/amplify_datastore_observe_test.dart | 2 +- .../test/amplify_datastore_query_test.dart | 2 +- .../test/amplify_datastore_save_test.dart | 2 +- ...lify_datastore_stream_controller_test.dart | 2 +- .../test/amplify_datastore_test.dart | 2 +- .../test/observe_query_executor_test.dart | 2 +- .../test/outbox_mutation_event_test.dart | 2 +- .../test/query_predicate_test.dart | 68 +++- .../test/query_sort_test.dart | 3 +- .../model_identifier_equals.json | 19 + .../model_identifier_group_equals.json | 26 ++ .../model_identifier_group_not_equals.json | 26 ++ .../model_identifier_not_equals.json | 19 + .../test/test_models/Blog.dart | 192 ---------- .../test/test_models/Comment.dart | 189 ---------- .../test/test_models/ModelProvider.dart | 65 ---- .../test/test_models/Post.dart | 311 ----------------- .../test/test_models/StringListTypeModel.dart | 112 ------ .../test/test_models/test_schema.graphql | 24 -- .../test/amplify_custom_type_schema_test.dart | 2 +- .../test/amplify_modelType_test.dart | 2 +- .../test/amplify_modelschema_test.dart | 51 +-- .../test/amplify_modelschema_to_map_test.dart | 47 ++- .../test/model_identifier_test.dart | 129 +++++++ .../test/query_snapshot_test.dart | 2 +- .../test/testData/Blog.dart | 189 ---------- .../test/testData/Comment.dart | 186 ---------- .../test/testData/ModelProvider.dart | 75 ---- .../test/testData/Post.dart | 308 ---------------- .../test/testData/testData_schema.graphql | 61 ---- .../lib/test_models}/Address.dart | 36 +- .../amplify_test/lib/test_models/Blog.dart | 76 +++- .../amplify_test/lib/test_models/Comment.dart | 68 +++- .../lib/test_models}/Contact.dart | 31 +- .../lib/test_models/FileMeta.dart | 12 +- .../lib/test_models/Inventory.dart | 328 ++++++++++++++++++ .../lib/test_models/ModelProvider.dart | 54 ++- .../lib/test_models}/Person.dart | 85 +++-- .../lib/test_models}/Phone.dart | 24 +- .../amplify_test/lib/test_models/Post.dart | 94 ++++- .../lib/test_models/PostWithAuthRules.dart} | 109 ++++-- .../amplify_test/lib/test_models/Product.dart | 268 ++++++++++++++ .../lib/test_models/S3Object.dart | 18 +- .../lib/test_models/StringListTypeModel.dart | 201 +++++++++++ .../lib/test_models/Warehouse.dart | 252 ++++++++++++++ .../lib/test_models/schema.graphql | 108 ++++++ .../test/graphql_helpers_test.dart | 6 +- 50 files changed, 1992 insertions(+), 1904 deletions(-) create mode 100644 packages/amplify_datastore/test/resources/query_predicate/model_identifier_equals.json create mode 100644 packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_equals.json create mode 100644 packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_not_equals.json create mode 100644 packages/amplify_datastore/test/resources/query_predicate/model_identifier_not_equals.json delete mode 100644 packages/amplify_datastore/test/test_models/Blog.dart delete mode 100644 packages/amplify_datastore/test/test_models/Comment.dart delete mode 100644 packages/amplify_datastore/test/test_models/ModelProvider.dart delete mode 100644 packages/amplify_datastore/test/test_models/Post.dart delete mode 100644 packages/amplify_datastore/test/test_models/StringListTypeModel.dart delete mode 100644 packages/amplify_datastore/test/test_models/test_schema.graphql create mode 100644 packages/amplify_datastore_plugin_interface/test/model_identifier_test.dart delete mode 100644 packages/amplify_datastore_plugin_interface/test/testData/Blog.dart delete mode 100644 packages/amplify_datastore_plugin_interface/test/testData/Comment.dart delete mode 100644 packages/amplify_datastore_plugin_interface/test/testData/ModelProvider.dart delete mode 100644 packages/amplify_datastore_plugin_interface/test/testData/Post.dart delete mode 100644 packages/amplify_datastore_plugin_interface/test/testData/testData_schema.graphql rename packages/{amplify_datastore_plugin_interface/test/testData => amplify_test/lib/test_models}/Address.dart (73%) rename packages/{amplify_datastore_plugin_interface/test/testData => amplify_test/lib/test_models}/Contact.dart (72%) create mode 100644 packages/amplify_test/lib/test_models/Inventory.dart rename packages/{amplify_datastore_plugin_interface/test/testData => amplify_test/lib/test_models}/Person.dart (67%) rename packages/{amplify_datastore_plugin_interface/test/testData => amplify_test/lib/test_models}/Phone.dart (65%) rename packages/{amplify_datastore_plugin_interface/test/testData/PostAuthComplex.dart => amplify_test/lib/test_models/PostWithAuthRules.dart} (51%) create mode 100644 packages/amplify_test/lib/test_models/Product.dart create mode 100644 packages/amplify_test/lib/test_models/StringListTypeModel.dart create mode 100644 packages/amplify_test/lib/test_models/Warehouse.dart create mode 100644 packages/amplify_test/lib/test_models/schema.graphql diff --git a/packages/amplify_datastore/test/amplify_datastore_clear_test.dart b/packages/amplify_datastore/test/amplify_datastore_clear_test.dart index 5832e6cde8..1bf398849e 100644 --- a/packages/amplify_datastore/test/amplify_datastore_clear_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_clear_test.dart @@ -17,7 +17,7 @@ import 'package:amplify_core/amplify_core.dart'; import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const MethodChannel dataStoreChannel = diff --git a/packages/amplify_datastore/test/amplify_datastore_custom_error_handler_test.dart b/packages/amplify_datastore/test/amplify_datastore_custom_error_handler_test.dart index 2d14e595b7..e11400cdf9 100644 --- a/packages/amplify_datastore/test/amplify_datastore_custom_error_handler_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_custom_error_handler_test.dart @@ -18,7 +18,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; // Utilized from: https://github.com/flutter/flutter/issues/63465 #CyrilHu // For mocking Native -> Dart diff --git a/packages/amplify_datastore/test/amplify_datastore_delete_test.dart b/packages/amplify_datastore/test/amplify_datastore_delete_test.dart index eb63e80515..a2835e0c6f 100644 --- a/packages/amplify_datastore/test/amplify_datastore_delete_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_delete_test.dart @@ -17,7 +17,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:amplify_test/amplify_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const MethodChannel dataStoreChannel = diff --git a/packages/amplify_datastore/test/amplify_datastore_observe_test.dart b/packages/amplify_datastore/test/amplify_datastore_observe_test.dart index b0e7472076..7cc6f11d19 100644 --- a/packages/amplify_datastore/test/amplify_datastore_observe_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_observe_test.dart @@ -17,7 +17,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const MethodChannel dataStoreChannel = diff --git a/packages/amplify_datastore/test/amplify_datastore_query_test.dart b/packages/amplify_datastore/test/amplify_datastore_query_test.dart index 87519f5a77..44f3f45710 100644 --- a/packages/amplify_datastore/test/amplify_datastore_query_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_query_test.dart @@ -18,7 +18,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const MethodChannel dataStoreChannel = diff --git a/packages/amplify_datastore/test/amplify_datastore_save_test.dart b/packages/amplify_datastore/test/amplify_datastore_save_test.dart index 81f9d73ce5..3cc4f26ed9 100644 --- a/packages/amplify_datastore/test/amplify_datastore_save_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_save_test.dart @@ -17,7 +17,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const MethodChannel dataStoreChannel = diff --git a/packages/amplify_datastore/test/amplify_datastore_stream_controller_test.dart b/packages/amplify_datastore/test/amplify_datastore_stream_controller_test.dart index ed95d6511a..01f380181e 100644 --- a/packages/amplify_datastore/test/amplify_datastore_stream_controller_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_stream_controller_test.dart @@ -20,7 +20,7 @@ import 'package:amplify_datastore/amplify_datastore_stream_controller.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const MethodChannel datastoreChannel = diff --git a/packages/amplify_datastore/test/amplify_datastore_test.dart b/packages/amplify_datastore/test/amplify_datastore_test.dart index 913791a133..d9c742fc33 100644 --- a/packages/amplify_datastore/test/amplify_datastore_test.dart +++ b/packages/amplify_datastore/test/amplify_datastore_test.dart @@ -17,7 +17,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/services.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { const mockSyncInterval = 3600; diff --git a/packages/amplify_datastore/test/observe_query_executor_test.dart b/packages/amplify_datastore/test/observe_query_executor_test.dart index e516eeed22..78a7e2b61b 100644 --- a/packages/amplify_datastore/test/observe_query_executor_test.dart +++ b/packages/amplify_datastore/test/observe_query_executor_test.dart @@ -18,7 +18,7 @@ import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_inte import 'package:flutter_test/flutter_test.dart'; import 'package:fake_async/fake_async.dart'; import '../lib/types/observe_query_executor.dart'; -import './test_models/Blog.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; var syncQueriesStartedEvent = DataStoreHubEvent( 'syncQueriesStarted', diff --git a/packages/amplify_datastore/test/outbox_mutation_event_test.dart b/packages/amplify_datastore/test/outbox_mutation_event_test.dart index 7852c8aacc..546f914e59 100644 --- a/packages/amplify_datastore/test/outbox_mutation_event_test.dart +++ b/packages/amplify_datastore/test/outbox_mutation_event_test.dart @@ -17,7 +17,7 @@ import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:amplify_test/amplify_test.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() async { var modelProvider = ModelProvider(); diff --git a/packages/amplify_datastore/test/query_predicate_test.dart b/packages/amplify_datastore/test/query_predicate_test.dart index 8d8136f21c..3871f000a9 100644 --- a/packages/amplify_datastore/test/query_predicate_test.dart +++ b/packages/amplify_datastore/test/query_predicate_test.dart @@ -18,8 +18,7 @@ import 'dart:io'; import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; import 'package:flutter_test/flutter_test.dart'; - -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -123,6 +122,69 @@ void main() { expect(testPredicate.serializeAsMap(), await getJsonFromFile('temporal_predicate.json')); }); + + test('when query by model identifier with eq()', () async { + final testPredicate = Inventory.MODEL_IDENTIFIER.eq( + InventoryModelIdentifier( + productID: 'product-id', + name: 'product-name', + warehouseID: 'warehouse-id', + region: 'some region', + ), + ); + + final serialized = testPredicate.serializeAsMap(); + expect(serialized, await getJsonFromFile('model_identifier_equals.json')); + }); + + test('when query by model identifier with ne()', () async { + final testPredicate = Inventory.MODEL_IDENTIFIER.ne( + InventoryModelIdentifier( + productID: 'product-id', + name: 'product-name', + warehouseID: 'warehouse-id', + region: 'some region', + ), + ); + + final serialized = testPredicate.serializeAsMap(); + expect(serialized, + await getJsonFromFile('model_identifier_not_equals.json')); + }); + + test('when query by model identifier with not(eq())', () async { + final testPredicate = not( + Inventory.MODEL_IDENTIFIER.eq( + InventoryModelIdentifier( + productID: 'product-id', + name: 'product-name', + warehouseID: 'warehouse-id', + region: 'some region', + ), + ), + ); + + final serialized = testPredicate.serializeAsMap(); + expect(serialized, + await getJsonFromFile('model_identifier_group_not_equals.json')); + }); + + test('when query by model identifier with not(ne())', () async { + final testPredicate = not( + Inventory.MODEL_IDENTIFIER.ne( + InventoryModelIdentifier( + productID: 'product-id', + name: 'product-name', + warehouseID: 'warehouse-id', + region: 'some region', + ), + ), + ); + + final serialized = testPredicate.serializeAsMap(); + expect(serialized, + await getJsonFromFile('model_identifier_group_equals.json')); + }); }); group('query predicate comparison', () { @@ -275,4 +337,6 @@ void main() { }); }); }); + + group("query by model identifier predicate", () {}); } diff --git a/packages/amplify_datastore/test/query_sort_test.dart b/packages/amplify_datastore/test/query_sort_test.dart index 3db16d81e0..745424c6f8 100644 --- a/packages/amplify_datastore/test/query_sort_test.dart +++ b/packages/amplify_datastore/test/query_sort_test.dart @@ -18,8 +18,7 @@ import 'dart:io'; import 'package:amplify_datastore/amplify_datastore.dart'; import 'package:flutter_test/flutter_test.dart'; - -import 'test_models/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/amplify_datastore/test/resources/query_predicate/model_identifier_equals.json b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_equals.json new file mode 100644 index 0000000000..f14ab765ac --- /dev/null +++ b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_equals.json @@ -0,0 +1,19 @@ +{ + "queryByIdentifierOperation": { + "operatorName": "equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } +} diff --git a/packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_equals.json b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_equals.json new file mode 100644 index 0000000000..6c7baece0e --- /dev/null +++ b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_equals.json @@ -0,0 +1,26 @@ +{ + "queryPredicateGroup": { + "type": "not", + "predicates": [ + { + "queryByIdentifierOperation": { + "operatorName": "not_equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } + } + ] + } +} diff --git a/packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_not_equals.json b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_not_equals.json new file mode 100644 index 0000000000..121219070c --- /dev/null +++ b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_group_not_equals.json @@ -0,0 +1,26 @@ +{ + "queryPredicateGroup": { + "type": "not", + "predicates": [ + { + "queryByIdentifierOperation": { + "operatorName": "equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } + } + ] + } +} diff --git a/packages/amplify_datastore/test/resources/query_predicate/model_identifier_not_equals.json b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_not_equals.json new file mode 100644 index 0000000000..0ef0745316 --- /dev/null +++ b/packages/amplify_datastore/test/resources/query_predicate/model_identifier_not_equals.json @@ -0,0 +1,19 @@ +{ + "queryByIdentifierOperation": { + "operatorName": "not_equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } +} diff --git a/packages/amplify_datastore/test/test_models/Blog.dart b/packages/amplify_datastore/test/test_models/Blog.dart deleted file mode 100644 index 004062c731..0000000000 --- a/packages/amplify_datastore/test/test_models/Blog.dart +++ /dev/null @@ -1,192 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// NOTE: This file is generated and may not follow lint rules defined in your app -// Generated files can be excluded from analysis in analysis_options.yaml -// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis - -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code - -import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart'; - -/** This is an auto generated class representing the Blog type in your schema. */ -@immutable -class Blog extends Model { - static const classType = const _BlogModelType(); - final String id; - final String? _name; - final List? _posts; - final TemporalDateTime? _createdAt; - final TemporalDateTime? _updatedAt; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - String get name { - try { - return _name!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - List? get posts { - return _posts; - } - - TemporalDateTime? get createdAt { - return _createdAt; - } - - TemporalDateTime? get updatedAt { - return _updatedAt; - } - - const Blog._internal( - {required this.id, required name, posts, createdAt, updatedAt}) - : _name = name, - _posts = posts, - _createdAt = createdAt, - _updatedAt = updatedAt; - - factory Blog({String? id, required String name, List? posts}) { - return Blog._internal( - id: id == null ? UUID.getUUID() : id, - name: name, - posts: posts != null ? List.unmodifiable(posts) : posts); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is Blog && - id == other.id && - _name == other._name && - DeepCollectionEquality().equals(_posts, other._posts); - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("Blog {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("name=" + "$_name" + ", "); - buffer.write("createdAt=" + - (_createdAt != null ? _createdAt!.format() : "null") + - ", "); - buffer.write( - "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - Blog copyWith({String? id, String? name, List? posts}) { - return Blog._internal( - id: id ?? this.id, name: name ?? this.name, posts: posts ?? this.posts); - } - - Blog.fromJson(Map json) - : id = json['id'], - _name = json['name'], - _posts = json['posts'] is List - ? (json['posts'] as List) - .where((e) => e?['serializedData'] != null) - .map((e) => Post.fromJson( - new Map.from(e['serializedData']))) - .toList() - : null, - _createdAt = json['createdAt'] != null - ? TemporalDateTime.fromString(json['createdAt']) - : null, - _updatedAt = json['updatedAt'] != null - ? TemporalDateTime.fromString(json['updatedAt']) - : null; - - Map toJson() => { - 'id': id, - 'name': _name, - 'posts': _posts?.map((Post? e) => e?.toJson()).toList(), - 'createdAt': _createdAt?.format(), - 'updatedAt': _updatedAt?.format() - }; - - static final QueryField ID = QueryField(fieldName: "id"); - static final QueryField NAME = QueryField(fieldName: "name"); - static final QueryField POSTS = QueryField( - fieldName: "posts", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Post).toString())); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "Blog"; - modelSchemaDefinition.pluralName = "Blogs"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Blog.NAME, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.string))); - - modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( - key: Blog.POSTS, - isRequired: false, - ofModelName: (Post).toString(), - associatedKey: Post.BLOG)); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'createdAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'updatedAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - }); -} - -class _BlogModelType extends ModelType { - const _BlogModelType(); - - @override - Blog fromJson(Map jsonData) { - return Blog.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore/test/test_models/Comment.dart b/packages/amplify_datastore/test/test_models/Comment.dart deleted file mode 100644 index 3f19b33059..0000000000 --- a/packages/amplify_datastore/test/test_models/Comment.dart +++ /dev/null @@ -1,189 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// NOTE: This file is generated and may not follow lint rules defined in your app -// Generated files can be excluded from analysis in analysis_options.yaml -// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis - -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code - -import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:flutter/foundation.dart'; - -/** This is an auto generated class representing the Comment type in your schema. */ -@immutable -class Comment extends Model { - static const classType = const _CommentModelType(); - final String id; - final Post? _post; - final String? _content; - final TemporalDateTime? _createdAt; - final TemporalDateTime? _updatedAt; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - Post? get post { - return _post; - } - - String get content { - try { - return _content!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - TemporalDateTime? get createdAt { - return _createdAt; - } - - TemporalDateTime? get updatedAt { - return _updatedAt; - } - - const Comment._internal( - {required this.id, post, required content, createdAt, updatedAt}) - : _post = post, - _content = content, - _createdAt = createdAt, - _updatedAt = updatedAt; - - factory Comment({String? id, Post? post, required String content}) { - return Comment._internal( - id: id == null ? UUID.getUUID() : id, post: post, content: content); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is Comment && - id == other.id && - _post == other._post && - _content == other._content; - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("Comment {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("post=" + (_post != null ? _post!.toString() : "null") + ", "); - buffer.write("content=" + "$_content" + ", "); - buffer.write("createdAt=" + - (_createdAt != null ? _createdAt!.format() : "null") + - ", "); - buffer.write( - "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - Comment copyWith({String? id, Post? post, String? content}) { - return Comment._internal( - id: id ?? this.id, - post: post ?? this.post, - content: content ?? this.content); - } - - Comment.fromJson(Map json) - : id = json['id'], - _post = json['post']?['serializedData'] != null - ? Post.fromJson( - new Map.from(json['post']['serializedData'])) - : null, - _content = json['content'], - _createdAt = json['createdAt'] != null - ? TemporalDateTime.fromString(json['createdAt']) - : null, - _updatedAt = json['updatedAt'] != null - ? TemporalDateTime.fromString(json['updatedAt']) - : null; - - Map toJson() => { - 'id': id, - 'post': _post?.toJson(), - 'content': _content, - 'createdAt': _createdAt?.format(), - 'updatedAt': _updatedAt?.format() - }; - - static final QueryField ID = QueryField(fieldName: "id"); - static final QueryField POST = QueryField( - fieldName: "post", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Post).toString())); - static final QueryField CONTENT = QueryField(fieldName: "content"); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "Comment"; - modelSchemaDefinition.pluralName = "Comments"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( - key: Comment.POST, - isRequired: false, - targetName: "postID", - ofModelName: (Post).toString())); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Comment.CONTENT, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.string))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'createdAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'updatedAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - }); -} - -class _CommentModelType extends ModelType { - const _CommentModelType(); - - @override - Comment fromJson(Map jsonData) { - return Comment.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore/test/test_models/ModelProvider.dart b/packages/amplify_datastore/test/test_models/ModelProvider.dart deleted file mode 100644 index fdf0333744..0000000000 --- a/packages/amplify_datastore/test/test_models/ModelProvider.dart +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// NOTE: This file is generated and may not follow lint rules defined in your app -// Generated files can be excluded from analysis in analysis_options.yaml -// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis - -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code - -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'Blog.dart'; -import 'Comment.dart'; -import 'Post.dart'; -import 'StringListTypeModel.dart'; - -export 'Blog.dart'; -export 'Comment.dart'; -export 'Post.dart'; -export 'StringListTypeModel.dart'; - -class ModelProvider implements ModelProviderInterface { - @override - String version = "f43670a12adedf95a96cd58377c6c2bc"; - @override - List modelSchemas = [ - Blog.schema, - Comment.schema, - Post.schema, - StringListTypeModel.schema - ]; - static final ModelProvider _instance = ModelProvider(); - @override - List customTypeSchemas = []; - - static ModelProvider get instance => _instance; - - ModelType getModelTypeByModelName(String modelName) { - switch (modelName) { - case "Blog": - return Blog.classType; - case "Comment": - return Comment.classType; - case "Post": - return Post.classType; - case "StringListTypeModel": - return StringListTypeModel.classType; - default: - throw Exception( - "Failed to find model in model provider for model name: " + - modelName); - } - } -} diff --git a/packages/amplify_datastore/test/test_models/Post.dart b/packages/amplify_datastore/test/test_models/Post.dart deleted file mode 100644 index 2d8620c36a..0000000000 --- a/packages/amplify_datastore/test/test_models/Post.dart +++ /dev/null @@ -1,311 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// NOTE: This file is generated and may not follow lint rules defined in your app -// Generated files can be excluded from analysis in analysis_options.yaml -// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis - -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code - -import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart'; - -/** This is an auto generated class representing the Post type in your schema. */ -@immutable -class Post extends Model { - static const classType = const _PostModelType(); - final String id; - final String? _title; - final int? _rating; - final TemporalDateTime? _created; - final int? _likeCount; - final Blog? _blog; - final List? _comments; - final TemporalDateTime? _createdAt; - final TemporalDateTime? _updatedAt; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - String get title { - try { - return _title!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - int get rating { - try { - return _rating!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - TemporalDateTime? get created { - return _created; - } - - int? get likeCount { - return _likeCount; - } - - Blog? get blog { - return _blog; - } - - List? get comments { - return _comments; - } - - TemporalDateTime? get createdAt { - return _createdAt; - } - - TemporalDateTime? get updatedAt { - return _updatedAt; - } - - const Post._internal( - {required this.id, - required title, - required rating, - created, - likeCount, - blog, - comments, - createdAt, - updatedAt}) - : _title = title, - _rating = rating, - _created = created, - _likeCount = likeCount, - _blog = blog, - _comments = comments, - _createdAt = createdAt, - _updatedAt = updatedAt; - - factory Post( - {String? id, - required String title, - required int rating, - TemporalDateTime? created, - int? likeCount, - Blog? blog, - List? comments}) { - return Post._internal( - id: id == null ? UUID.getUUID() : id, - title: title, - rating: rating, - created: created, - likeCount: likeCount, - blog: blog, - comments: - comments != null ? List.unmodifiable(comments) : comments); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is Post && - id == other.id && - _title == other._title && - _rating == other._rating && - _created == other._created && - _likeCount == other._likeCount && - _blog == other._blog && - DeepCollectionEquality().equals(_comments, other._comments); - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("Post {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("title=" + "$_title" + ", "); - buffer.write( - "rating=" + (_rating != null ? _rating!.toString() : "null") + ", "); - buffer.write( - "created=" + (_created != null ? _created!.format() : "null") + ", "); - buffer.write("likeCount=" + - (_likeCount != null ? _likeCount!.toString() : "null") + - ", "); - buffer.write("blog=" + (_blog != null ? _blog!.toString() : "null") + ", "); - buffer.write("createdAt=" + - (_createdAt != null ? _createdAt!.format() : "null") + - ", "); - buffer.write( - "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - Post copyWith( - {String? id, - String? title, - int? rating, - TemporalDateTime? created, - int? likeCount, - Blog? blog, - List? comments}) { - return Post._internal( - id: id ?? this.id, - title: title ?? this.title, - rating: rating ?? this.rating, - created: created ?? this.created, - likeCount: likeCount ?? this.likeCount, - blog: blog ?? this.blog, - comments: comments ?? this.comments); - } - - Post.fromJson(Map json) - : id = json['id'], - _title = json['title'], - _rating = (json['rating'] as num?)?.toInt(), - _created = json['created'] != null - ? TemporalDateTime.fromString(json['created']) - : null, - _likeCount = (json['likeCount'] as num?)?.toInt(), - _blog = json['blog']?['serializedData'] != null - ? Blog.fromJson( - new Map.from(json['blog']['serializedData'])) - : null, - _comments = json['comments'] is List - ? (json['comments'] as List) - .where((e) => e?['serializedData'] != null) - .map((e) => Comment.fromJson( - new Map.from(e['serializedData']))) - .toList() - : null, - _createdAt = json['createdAt'] != null - ? TemporalDateTime.fromString(json['createdAt']) - : null, - _updatedAt = json['updatedAt'] != null - ? TemporalDateTime.fromString(json['updatedAt']) - : null; - - Map toJson() => { - 'id': id, - 'title': _title, - 'rating': _rating, - 'created': _created?.format(), - 'likeCount': _likeCount, - 'blog': _blog?.toJson(), - 'comments': _comments?.map((Comment? e) => e?.toJson()).toList(), - 'createdAt': _createdAt?.format(), - 'updatedAt': _updatedAt?.format() - }; - - static final QueryField ID = QueryField(fieldName: "id"); - static final QueryField TITLE = QueryField(fieldName: "title"); - static final QueryField RATING = QueryField(fieldName: "rating"); - static final QueryField CREATED = QueryField(fieldName: "created"); - static final QueryField LIKECOUNT = QueryField(fieldName: "likeCount"); - static final QueryField BLOG = QueryField( - fieldName: "blog", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Blog).toString())); - static final QueryField COMMENTS = QueryField( - fieldName: "comments", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Comment).toString())); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "Post"; - modelSchemaDefinition.pluralName = "Posts"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.TITLE, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.string))); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.RATING, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.int))); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.CREATED, - isRequired: false, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.LIKECOUNT, - isRequired: false, - ofType: ModelFieldType(ModelFieldTypeEnum.int))); - - modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( - key: Post.BLOG, - isRequired: false, - targetName: "blogID", - ofModelName: (Blog).toString())); - - modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( - key: Post.COMMENTS, - isRequired: false, - ofModelName: (Comment).toString(), - associatedKey: Comment.POST)); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'createdAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'updatedAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - }); -} - -class _PostModelType extends ModelType { - const _PostModelType(); - - @override - Post fromJson(Map jsonData) { - return Post.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore/test/test_models/StringListTypeModel.dart b/packages/amplify_datastore/test/test_models/StringListTypeModel.dart deleted file mode 100644 index 56b1cc726d..0000000000 --- a/packages/amplify_datastore/test/test_models/StringListTypeModel.dart +++ /dev/null @@ -1,112 +0,0 @@ -/* -* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// ignore_for_file: public_member_api_docs - -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart'; - -/** This is an auto generated class representing the StringListTypeModel type in your schema. */ -@immutable -class StringListTypeModel extends Model { - static const classType = const _StringListTypeModelModelType(); - final String id; - final List? _value; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - List? get value { - return _value; - } - - const StringListTypeModel._internal({required this.id, value}) - : _value = value; - - factory StringListTypeModel({String? id, List? value}) { - return StringListTypeModel._internal( - id: id == null ? UUID.getUUID() : id, - value: value != null ? List.unmodifiable(value) : value); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is StringListTypeModel && - id == other.id && - DeepCollectionEquality().equals(_value, other._value); - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("StringListTypeModel {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("value=" + (_value != null ? _value!.toString() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - StringListTypeModel copyWith({String? id, List? value}) { - return StringListTypeModel(id: id ?? this.id, value: value ?? this.value); - } - - StringListTypeModel.fromJson(Map json) - : id = json['id'], - _value = json['value']?.cast(); - - Map toJson() => {'id': id, 'value': _value}; - - static final QueryField ID = QueryField(fieldName: "id"); - static final QueryField VALUE = QueryField(fieldName: "value"); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "StringListTypeModel"; - modelSchemaDefinition.pluralName = "StringListTypeModels"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: StringListTypeModel.VALUE, - isRequired: false, - isArray: true, - ofType: ModelFieldType(ModelFieldTypeEnum.collection, - ofModelName: describeEnum(ModelFieldTypeEnum.string)))); - }); -} - -class _StringListTypeModelModelType extends ModelType { - const _StringListTypeModelModelType(); - - @override - StringListTypeModel fromJson(Map jsonData) { - return StringListTypeModel.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore/test/test_models/test_schema.graphql b/packages/amplify_datastore/test/test_models/test_schema.graphql deleted file mode 100644 index 6189cc977e..0000000000 --- a/packages/amplify_datastore/test/test_models/test_schema.graphql +++ /dev/null @@ -1,24 +0,0 @@ -# This schema can be used to regenerate the test models that are in this folder -type Blog @model { - id: ID! - name: String! - posts: [Post] @connection(keyName: "byBlog", fields: ["id"]) -} - -type Post @model @key(name: "byBlog", fields: ["blogID"]) { - id: ID! - title: String! - rating: Int! - created: AWSDateTime - likeCount: Int - blogID: ID! - blog: Blog @connection(fields: ["blogID"]) - comments: [Comment] @connection(keyName: "byPost", fields: ["id"]) -} - -type Comment @model @key(name: "byPost", fields: ["postID", "content"]) { - id: ID! - postID: ID! - post: Post @connection(fields: ["postID"]) - content: String! -} diff --git a/packages/amplify_datastore_plugin_interface/test/amplify_custom_type_schema_test.dart b/packages/amplify_datastore_plugin_interface/test/amplify_custom_type_schema_test.dart index 05e47cea89..efbb2adbb8 100644 --- a/packages/amplify_datastore_plugin_interface/test/amplify_custom_type_schema_test.dart +++ b/packages/amplify_datastore_plugin_interface/test/amplify_custom_type_schema_test.dart @@ -16,7 +16,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'testData/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; /* Tests use below schema diff --git a/packages/amplify_datastore_plugin_interface/test/amplify_modelType_test.dart b/packages/amplify_datastore_plugin_interface/test/amplify_modelType_test.dart index bac74c5425..f8f6ca2a79 100644 --- a/packages/amplify_datastore_plugin_interface/test/amplify_modelType_test.dart +++ b/packages/amplify_datastore_plugin_interface/test/amplify_modelType_test.dart @@ -15,7 +15,7 @@ import 'package:flutter_test/flutter_test.dart'; -import 'testData/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { test('Comment.classType generates proper json from serializedMap modelschema', diff --git a/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_test.dart b/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_test.dart index 50112b0683..709b095962 100644 --- a/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_test.dart +++ b/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_test.dart @@ -22,15 +22,18 @@ We need to verify that each conversion step (->) is done correctly and each stat import 'package:amplify_core/amplify_core.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'testData/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { test('Blog codegen model generates modelschema with proper fields', () async { /* type Blog @model { - id: ID! + id: ID! @primaryKey name: String! - posts: [Post] @connection(keyName: "byBlog", fields: ["id"]) + createdAt: AWSDateTime + file: S3Object + files: [S3Object] + posts: [Post] @hasMany(indexName: "byBlog", fields: ["id"]) } */ @@ -73,13 +76,13 @@ void main() { test('Comment codegen model generates modelschema with proper fields', () async { /* - type Comment @model @key(name: "byPost", fields: ["postID", "content"]) { + type Comment @model { id: ID! - postID: ID! - post: Post @connection(fields: ["postID"]) + postID: ID! @index(name: "byPost", sortKeyFields: ["content"]) + post: Post @belongsTo(fields: ["postID"]) content: String! } - */ + */ ModelSchema commentSchema = Comment.schema; @@ -117,14 +120,17 @@ void main() { test('Post codegen model generates modelschema with proper fields', () async { /* - type Post @model @key(name: "byBlog", fields: ["blogID"]) { + type Post @model { id: ID! title: String! - blogID: ID! - blog: Blog @connection(fields: ["blogID"]) - comments: [Comment] @connection(keyName: "byPost", fields: ["id"]) + rating: Int! + created: AWSDateTime + likeCount: Int + blogID: ID! @index(name: "byBlog") + blog: Blog @belongsTo(fields: ["blogID"]) + comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"]) } - */ + */ ModelSchema postSchema = Post.schema; @@ -163,28 +169,33 @@ void main() { test('PostAuthComplex codegen model generates modelschema with proper fields', () async { /* - type PostAuthComplex + type PostWithAuthRules @model @auth( rules: [ - { allow: owner, ownerField: "owner", operations: [create, update, delete, read] }, - ]) - { + { + allow: owner + ownerField: "owner" + operations: [create, update, delete, read] + } + ] + ) { id: ID! title: String! owner: String } - */ + */ - ModelSchema postSchema = PostAuthComplex.schema; + ModelSchema postSchema = PostWithAuthRules.schema; - expect(postSchema.name, "PostAuthComplex"); - expect(postSchema.pluralName, "PostAuthComplexes"); + expect(postSchema.name, "PostWithAuthRules"); + expect(postSchema.pluralName, "PostWithAuthRules"); expect(postSchema.authRules, [ AuthRule( authStrategy: AuthStrategy.OWNER, ownerField: "owner", identityClaim: "cognito:username", + provider: AuthRuleProvider.USERPOOLS, operations: [ ModelOperation.CREATE, ModelOperation.UPDATE, diff --git a/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_to_map_test.dart b/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_to_map_test.dart index 7f03c3f595..a3ab58a473 100644 --- a/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_to_map_test.dart +++ b/packages/amplify_datastore_plugin_interface/test/amplify_modelschema_to_map_test.dart @@ -16,7 +16,7 @@ import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'testData/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { test('Blog codegen model generates modelschema with proper fields', () async { @@ -26,6 +26,12 @@ void main() { expect(map, { 'name': "Blog", 'pluralName': "Blogs", + 'indexes': [ + { + 'name': null, + 'fields': ['id'] + } + ], 'fields': { 'id': { 'name': "id", @@ -41,6 +47,23 @@ void main() { 'isArray': false, 'isReadOnly': false, }, + 'file': { + 'name': 'file', + 'type': {'fieldType': 'embedded', 'ofCustomTypeName': 'S3Object'}, + 'isRequired': false, + 'isArray': false, + 'isReadOnly': false + }, + 'files': { + 'name': 'files', + 'type': { + 'fieldType': 'embeddedCollection', + 'ofCustomTypeName': 'S3Object' + }, + 'isRequired': false, + 'isArray': true, + 'isReadOnly': false + }, 'posts': { 'name': "posts", 'type': {'fieldType': 'collection', 'ofModelName': "Post"}, @@ -58,7 +81,8 @@ void main() { 'type': {'fieldType': 'dateTime'}, 'isRequired': false, 'isArray': false, - 'isReadOnly': true + // Note that the testing overrides the readonly field createdAt + 'isReadOnly': false }, 'updatedAt': { 'name': 'updatedAt', @@ -79,6 +103,12 @@ void main() { expect(map, { 'name': 'Comment', 'pluralName': 'Comments', + 'indexes': [ + { + 'name': 'byPost', + 'fields': ['postID', 'content'] + } + ], 'fields': { 'id': { 'name': 'id', @@ -131,6 +161,12 @@ void main() { expect(map, { 'name': 'Post', 'pluralName': 'Posts', + 'indexes': [ + { + 'name': 'byBlog', + 'fields': ['blogID'] + } + ], 'fields': { 'id': { 'name': 'id', @@ -211,17 +247,18 @@ void main() { test('PostAuthComplex codegen model generates modelschema with proper fields', () async { - ModelSchema postAuthComplexSchema = PostAuthComplex.schema; + ModelSchema postAuthComplexSchema = PostWithAuthRules.schema; Map map = postAuthComplexSchema.toMap(); expect(map, { - 'name': 'PostAuthComplex', - 'pluralName': 'PostAuthComplexes', + 'name': 'PostWithAuthRules', + 'pluralName': 'PostWithAuthRules', 'authRules': [ { 'authStrategy': 'OWNER', 'ownerField': 'owner', 'identityClaim': 'cognito:username', + 'provider': 'USERPOOLS', 'operations': ['CREATE', 'UPDATE', 'DELETE', 'READ'] } ], diff --git a/packages/amplify_datastore_plugin_interface/test/model_identifier_test.dart b/packages/amplify_datastore_plugin_interface/test/model_identifier_test.dart new file mode 100644 index 0000000000..60600be6aa --- /dev/null +++ b/packages/amplify_datastore_plugin_interface/test/model_identifier_test.dart @@ -0,0 +1,129 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the 'license' file accompanying this file. This file is distributed + * on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; + +void main() { + const testId = 'test-id-123'; + test('modelIdentifier getter of a model with non-custom primary', () { + // type Post @model { + // id: ID! + // title: String! + // rating: Int! + // } + var post = Post(id: testId, title: 'test blog', rating: 10); + expect(post.modelIdentifier, PostModelIdentifier(id: testId)); + expect(post.modelIdentifier.serializeAsList(), [ + {'id': testId} + ]); + expect(post.modelIdentifier.serializeAsMap(), {'id': testId}); + expect(post.modelIdentifier.serializeAsList(), [ + {'id': testId} + ]); + expect(post.modelIdentifier.serializeAsString(), testId); + }); + + test( + 'modelIdentifier getter of a model with id field as the custom primary key', + () { + // type Blog @model { + // id: ID! @primaryKey + // name: String! + // } + var blog = Blog(id: testId, name: 'test blog'); + expect(blog.modelIdentifier, BlogModelIdentifier(id: testId)); + expect(blog.modelIdentifier.serializeAsMap(), {'id': testId}); + expect(blog.modelIdentifier.serializeAsList(), [ + {'id': testId} + ]); + expect(blog.modelIdentifier.serializeAsString(), testId); + }); + + test( + 'modelIdentifier getter of a model with id field as a part of composite custom primary key', + () { + // type Warehouse @model { + // id: ID! @primaryKey(sortKeyFields: ["name", "region"]) + // name: String! + // region: String! + // } + final testData = { + 'id': testId, + 'name': 'warehouse A', + 'region': 'west-ca', + }; + var warehouse = Warehouse.fromJson(testData); + expect( + warehouse.modelIdentifier, + WarehouseModelIdentifier( + id: testData['id']!, + name: testData['name']!, + region: testData['region']!, + )); + expect(warehouse.modelIdentifier.serializeAsMap(), testData); + expect(warehouse.modelIdentifier.serializeAsList(), + testData.entries.map((e) => ({e.key: e.value})).toList()); + expect(warehouse.modelIdentifier.serializeAsString(), + testData.values.join('#')); + }); + + test('modelIdentifier getter of a model with custom primary key', () { + // type Product @model { + // productID: ID! @primaryKey + // name: String! + // amount: Int! + // } + var product = Product(productID: testId, name: 'a product', amount: 5); + expect(product.modelIdentifier, ProductModelIdentifier(productID: testId)); + expect(product.modelIdentifier.serializeAsMap(), {'productID': testId}); + expect(product.modelIdentifier.serializeAsList(), [ + {'productID': testId} + ]); + expect(product.modelIdentifier.serializeAsString(), testId); + }); + + test('modelIdentifier getter of a model with composite custom primary key', + () { + // type Inventory @model { + // productID: String! + // @primaryKey(sortKeyFields: ["name", "warehouseID", "region"]) + // name: String! + // warehouseID: ID! + // region: String! + // } + final testData = { + 'productID': testId, + 'name': 'InventoryB', + 'warehouseID': 'warehouse-123', + 'region': 'west-ca' + }; + var inventory = Inventory.fromJson(testData); + expect( + inventory.modelIdentifier, + InventoryModelIdentifier( + productID: testData['productID']!, + name: testData['name']!, + warehouseID: testData['warehouseID']!, + region: testData['region']!, + ), + ); + expect(inventory.modelIdentifier.serializeAsMap(), testData); + expect(inventory.modelIdentifier.serializeAsList(), + testData.entries.map((e) => ({e.key: e.value})).toList()); + expect(inventory.modelIdentifier.serializeAsString(), + testData.values.join('#')); + }); +} diff --git a/packages/amplify_datastore_plugin_interface/test/query_snapshot_test.dart b/packages/amplify_datastore_plugin_interface/test/query_snapshot_test.dart index 3e2cd168a3..89cf319eb3 100644 --- a/packages/amplify_datastore_plugin_interface/test/query_snapshot_test.dart +++ b/packages/amplify_datastore_plugin_interface/test/query_snapshot_test.dart @@ -16,7 +16,7 @@ import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'testData/ModelProvider.dart'; +import 'package:amplify_test/test_models/ModelProvider.dart'; void main() { group('QuerySnapshot', () { diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Blog.dart b/packages/amplify_datastore_plugin_interface/test/testData/Blog.dart deleted file mode 100644 index b4460fd998..0000000000 --- a/packages/amplify_datastore_plugin_interface/test/testData/Blog.dart +++ /dev/null @@ -1,189 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart'; - -// ignore_for_file: public_member_api_docs - -import 'ModelProvider.dart'; - -/** This is an auto generated class representing the Blog type in your schema. */ -@immutable -class Blog extends Model { - static const classType = const _BlogModelType(); - final String id; - final String? _name; - final List? _posts; - final TemporalDateTime? _createdAt; - final TemporalDateTime? _updatedAt; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - String get name { - try { - return _name!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - List? get posts { - return _posts; - } - - TemporalDateTime? get createdAt { - return _createdAt; - } - - TemporalDateTime? get updatedAt { - return _updatedAt; - } - - const Blog._internal( - {required this.id, required name, posts, createdAt, updatedAt}) - : _name = name, - _posts = posts, - _createdAt = createdAt, - _updatedAt = updatedAt; - - factory Blog({String? id, required String name, List? posts}) { - return Blog._internal( - id: id == null ? UUID.getUUID() : id, - name: name, - posts: posts != null ? List.unmodifiable(posts) : posts); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is Blog && - id == other.id && - _name == other._name && - DeepCollectionEquality().equals(_posts, other._posts); - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("Blog {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("name=" + "$_name" + ", "); - buffer.write("createdAt=" + - (_createdAt != null ? _createdAt!.format() : "null") + - ", "); - buffer.write( - "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - Blog copyWith({String? id, String? name, List? posts}) { - return Blog._internal( - id: id ?? this.id, name: name ?? this.name, posts: posts ?? this.posts); - } - - Blog.fromJson(Map json) - : id = json['id'], - _name = json['name'], - _posts = json['posts'] is List - ? (json['posts'] as List) - .where((e) => e?['serializedData'] != null) - .map((e) => Post.fromJson( - new Map.from(e['serializedData']))) - .toList() - : null, - _createdAt = json['createdAt'] != null - ? TemporalDateTime.fromString(json['createdAt']) - : null, - _updatedAt = json['updatedAt'] != null - ? TemporalDateTime.fromString(json['updatedAt']) - : null; - - Map toJson() => { - 'id': id, - 'name': _name, - 'posts': _posts?.map((Post? e) => e?.toJson()).toList(), - 'createdAt': _createdAt?.format(), - 'updatedAt': _updatedAt?.format() - }; - - static final QueryField ID = QueryField(fieldName: "blog.id"); - static final QueryField NAME = QueryField(fieldName: "name"); - static final QueryField POSTS = QueryField( - fieldName: "posts", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Post).toString())); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "Blog"; - modelSchemaDefinition.pluralName = "Blogs"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Blog.NAME, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.string))); - - modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( - key: Blog.POSTS, - isRequired: false, - ofModelName: (Post).toString(), - associatedKey: Post.BLOG)); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'createdAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'updatedAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - }); -} - -class _BlogModelType extends ModelType { - const _BlogModelType(); - - @override - Blog fromJson(Map jsonData) { - return Blog.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Comment.dart b/packages/amplify_datastore_plugin_interface/test/testData/Comment.dart deleted file mode 100644 index 09592f8c7e..0000000000 --- a/packages/amplify_datastore_plugin_interface/test/testData/Comment.dart +++ /dev/null @@ -1,186 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:flutter/foundation.dart'; - -// ignore_for_file: public_member_api_docs - -import 'ModelProvider.dart'; - -/** This is an auto generated class representing the Comment type in your schema. */ -@immutable -class Comment extends Model { - static const classType = const _CommentModelType(); - final String id; - final Post? _post; - final String? _content; - final TemporalDateTime? _createdAt; - final TemporalDateTime? _updatedAt; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - Post? get post { - return _post; - } - - String get content { - try { - return _content!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - TemporalDateTime? get createdAt { - return _createdAt; - } - - TemporalDateTime? get updatedAt { - return _updatedAt; - } - - const Comment._internal( - {required this.id, post, required content, createdAt, updatedAt}) - : _post = post, - _content = content, - _createdAt = createdAt, - _updatedAt = updatedAt; - - factory Comment({String? id, Post? post, required String content}) { - return Comment._internal( - id: id == null ? UUID.getUUID() : id, post: post, content: content); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is Comment && - id == other.id && - _post == other._post && - _content == other._content; - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("Comment {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("post=" + (_post != null ? _post!.toString() : "null") + ", "); - buffer.write("content=" + "$_content" + ", "); - buffer.write("createdAt=" + - (_createdAt != null ? _createdAt!.format() : "null") + - ", "); - buffer.write( - "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - Comment copyWith({String? id, Post? post, String? content}) { - return Comment._internal( - id: id ?? this.id, - post: post ?? this.post, - content: content ?? this.content); - } - - Comment.fromJson(Map json) - : id = json['id'], - _post = json['post']?['serializedData'] != null - ? Post.fromJson( - new Map.from(json['post']['serializedData'])) - : null, - _content = json['content'], - _createdAt = json['createdAt'] != null - ? TemporalDateTime.fromString(json['createdAt']) - : null, - _updatedAt = json['updatedAt'] != null - ? TemporalDateTime.fromString(json['updatedAt']) - : null; - - Map toJson() => { - 'id': id, - 'post': _post?.toJson(), - 'content': _content, - 'createdAt': _createdAt?.format(), - 'updatedAt': _updatedAt?.format() - }; - - static final QueryField ID = QueryField(fieldName: "comment.id"); - static final QueryField POST = QueryField( - fieldName: "post", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Post).toString())); - static final QueryField CONTENT = QueryField(fieldName: "content"); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "Comment"; - modelSchemaDefinition.pluralName = "Comments"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( - key: Comment.POST, - isRequired: false, - targetName: "postID", - ofModelName: (Post).toString())); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Comment.CONTENT, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.string))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'createdAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'updatedAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - }); -} - -class _CommentModelType extends ModelType { - const _CommentModelType(); - - @override - Comment fromJson(Map jsonData) { - return Comment.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/ModelProvider.dart b/packages/amplify_datastore_plugin_interface/test/testData/ModelProvider.dart deleted file mode 100644 index 0039214f48..0000000000 --- a/packages/amplify_datastore_plugin_interface/test/testData/ModelProvider.dart +++ /dev/null @@ -1,75 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// ignore_for_file: public_member_api_docs - -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; - -import 'Address.dart'; -import 'Blog.dart'; -import 'Comment.dart'; -import 'Contact.dart'; -import 'Person.dart'; -import 'Phone.dart'; -import 'Post.dart'; -import 'PostAuthComplex.dart'; - -export 'Address.dart'; -export 'Blog.dart'; -export 'Comment.dart'; -export 'Contact.dart'; -export 'Person.dart'; -export 'Phone.dart'; -export 'Post.dart'; -export 'PostAuthComplex.dart'; - -class ModelProvider implements ModelProviderInterface { - @override - String version = "836a1f8cc4a4adc493165acc7168289e"; - @override - List modelSchemas = [ - Blog.schema, - Comment.schema, - Post.schema, - PostAuthComplex.schema - ]; - static final ModelProvider _instance = ModelProvider(); - @override - List customTypeSchemas = [ - Address.schema, - Contact.schema, - Person.schema, - Phone.schema - ]; - - static ModelProvider get instance => _instance; - - ModelType getModelTypeByModelName(String modelName) { - switch (modelName) { - case "Blog": - return Blog.classType; - case "Comment": - return Comment.classType; - case "Post": - return Post.classType; - case "PostAuthComplex": - return PostAuthComplex.classType; - default: - throw Exception( - "Failed to find model in model provider for model name: " + - modelName); - } - } -} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Post.dart b/packages/amplify_datastore_plugin_interface/test/testData/Post.dart deleted file mode 100644 index 3ca5c324e4..0000000000 --- a/packages/amplify_datastore_plugin_interface/test/testData/Post.dart +++ /dev/null @@ -1,308 +0,0 @@ -/* -* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart'; - -// ignore_for_file: public_member_api_docs - -import 'ModelProvider.dart'; - -/** This is an auto generated class representing the Post type in your schema. */ -@immutable -class Post extends Model { - static const classType = const _PostModelType(); - final String id; - final String? _title; - final int? _rating; - final TemporalDateTime? _created; - final int? _likeCount; - final Blog? _blog; - final List? _comments; - final TemporalDateTime? _createdAt; - final TemporalDateTime? _updatedAt; - - @override - getInstanceType() => classType; - - @override - String getId() { - return id; - } - - String get title { - try { - return _title!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - int get rating { - try { - return _rating!; - } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages - .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages - .codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString()); - } - } - - TemporalDateTime? get created { - return _created; - } - - int? get likeCount { - return _likeCount; - } - - Blog? get blog { - return _blog; - } - - List? get comments { - return _comments; - } - - TemporalDateTime? get createdAt { - return _createdAt; - } - - TemporalDateTime? get updatedAt { - return _updatedAt; - } - - const Post._internal( - {required this.id, - required title, - required rating, - created, - likeCount, - blog, - comments, - createdAt, - updatedAt}) - : _title = title, - _rating = rating, - _created = created, - _likeCount = likeCount, - _blog = blog, - _comments = comments, - _createdAt = createdAt, - _updatedAt = updatedAt; - - factory Post( - {String? id, - required String title, - required int rating, - TemporalDateTime? created, - int? likeCount, - Blog? blog, - List? comments}) { - return Post._internal( - id: id == null ? UUID.getUUID() : id, - title: title, - rating: rating, - created: created, - likeCount: likeCount, - blog: blog, - comments: - comments != null ? List.unmodifiable(comments) : comments); - } - - bool equals(Object other) { - return this == other; - } - - @override - bool operator ==(Object other) { - if (identical(other, this)) return true; - return other is Post && - id == other.id && - _title == other._title && - _rating == other._rating && - _created == other._created && - _likeCount == other._likeCount && - _blog == other._blog && - DeepCollectionEquality().equals(_comments, other._comments); - } - - @override - int get hashCode => toString().hashCode; - - @override - String toString() { - var buffer = new StringBuffer(); - - buffer.write("Post {"); - buffer.write("id=" + "$id" + ", "); - buffer.write("title=" + "$_title" + ", "); - buffer.write( - "rating=" + (_rating != null ? _rating!.toString() : "null") + ", "); - buffer.write( - "created=" + (_created != null ? _created!.format() : "null") + ", "); - buffer.write("likeCount=" + - (_likeCount != null ? _likeCount!.toString() : "null") + - ", "); - buffer.write("blog=" + (_blog != null ? _blog!.toString() : "null") + ", "); - buffer.write("createdAt=" + - (_createdAt != null ? _createdAt!.format() : "null") + - ", "); - buffer.write( - "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); - buffer.write("}"); - - return buffer.toString(); - } - - Post copyWith( - {String? id, - String? title, - int? rating, - TemporalDateTime? created, - int? likeCount, - Blog? blog, - List? comments}) { - return Post._internal( - id: id ?? this.id, - title: title ?? this.title, - rating: rating ?? this.rating, - created: created ?? this.created, - likeCount: likeCount ?? this.likeCount, - blog: blog ?? this.blog, - comments: comments ?? this.comments); - } - - Post.fromJson(Map json) - : id = json['id'], - _title = json['title'], - _rating = (json['rating'] as num?)?.toInt(), - _created = json['created'] != null - ? TemporalDateTime.fromString(json['created']) - : null, - _likeCount = (json['likeCount'] as num?)?.toInt(), - _blog = json['blog']?['serializedData'] != null - ? Blog.fromJson( - new Map.from(json['blog']['serializedData'])) - : null, - _comments = json['comments'] is List - ? (json['comments'] as List) - .where((e) => e?['serializedData'] != null) - .map((e) => Comment.fromJson( - new Map.from(e['serializedData']))) - .toList() - : null, - _createdAt = json['createdAt'] != null - ? TemporalDateTime.fromString(json['createdAt']) - : null, - _updatedAt = json['updatedAt'] != null - ? TemporalDateTime.fromString(json['updatedAt']) - : null; - - Map toJson() => { - 'id': id, - 'title': _title, - 'rating': _rating, - 'created': _created?.format(), - 'likeCount': _likeCount, - 'blog': _blog?.toJson(), - 'comments': _comments?.map((Comment? e) => e?.toJson()).toList(), - 'createdAt': _createdAt?.format(), - 'updatedAt': _updatedAt?.format() - }; - - static final QueryField ID = QueryField(fieldName: "post.id"); - static final QueryField TITLE = QueryField(fieldName: "title"); - static final QueryField RATING = QueryField(fieldName: "rating"); - static final QueryField CREATED = QueryField(fieldName: "created"); - static final QueryField LIKECOUNT = QueryField(fieldName: "likeCount"); - static final QueryField BLOG = QueryField( - fieldName: "blog", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Blog).toString())); - static final QueryField COMMENTS = QueryField( - fieldName: "comments", - fieldType: ModelFieldType(ModelFieldTypeEnum.model, - ofModelName: (Comment).toString())); - static var schema = - Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "Post"; - modelSchemaDefinition.pluralName = "Posts"; - - modelSchemaDefinition.addField(ModelFieldDefinition.id()); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.TITLE, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.string))); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.RATING, - isRequired: true, - ofType: ModelFieldType(ModelFieldTypeEnum.int))); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.CREATED, - isRequired: false, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: Post.LIKECOUNT, - isRequired: false, - ofType: ModelFieldType(ModelFieldTypeEnum.int))); - - modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( - key: Post.BLOG, - isRequired: false, - targetName: "blogID", - ofModelName: (Blog).toString())); - - modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( - key: Post.COMMENTS, - isRequired: false, - ofModelName: (Comment).toString(), - associatedKey: Comment.POST)); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'createdAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - - modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( - fieldName: 'updatedAt', - isRequired: false, - isReadOnly: true, - ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); - }); -} - -class _PostModelType extends ModelType { - const _PostModelType(); - - @override - Post fromJson(Map jsonData) { - return Post.fromJson(jsonData); - } -} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/testData_schema.graphql b/packages/amplify_datastore_plugin_interface/test/testData/testData_schema.graphql deleted file mode 100644 index afe5b0e49d..0000000000 --- a/packages/amplify_datastore_plugin_interface/test/testData/testData_schema.graphql +++ /dev/null @@ -1,61 +0,0 @@ -# This schema can be used to regenerate the test models that are in this folder -type Blog @model { - id: ID! - name: String! - posts: [Post] @connection(keyName: "byBlog", fields: ["id"]) -} - -type Post @model @key(name: "byBlog", fields: ["blogID"]) { - id: ID! - title: String! - rating: Int! - created: AWSDateTime - likeCount: Int - blogID: ID! - blog: Blog @connection(fields: ["blogID"]) - comments: [Comment] @connection(keyName: "byPost", fields: ["id"]) -} - -type PostAuthComplex - @model - @auth( - rules: [ - { allow: owner, ownerField: "owner", operations: [create, update, delete, read] }, - ]) -{ - id: ID! - title: String! - owner: String -} - -type Comment @model @key(name: "byPost", fields: ["postID", "content"]) { - id: ID! - postID: ID! - post: Post @connection(fields: ["postID"]) - content: String! -} - -type Address { - line1: String! - line2: String - city: String! - state: String! - postalCode: String! -} - -type Person { - name: String! - propertiesAddresses: [Address] - contact: Contact! -} - -type Phone { - country: String! - number: String! -} - -type Contact { - email: String! - phone: Phone! - mailingAddresses: [Address] -} \ No newline at end of file diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Address.dart b/packages/amplify_test/lib/test_models/Address.dart similarity index 73% rename from packages/amplify_datastore_plugin_interface/test/testData/Address.dart rename to packages/amplify_test/lib/test_models/Address.dart index adbc9d186b..837db5574c 100644 --- a/packages/amplify_datastore_plugin_interface/test/testData/Address.dart +++ b/packages/amplify_test/lib/test_models/Address.dart @@ -13,12 +13,16 @@ * permissions and limitations under the License. */ -// ignore_for_file: public_member_api_docs +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the Address type in your schema. */ +/// This is an auto generated class representing the Address type in your schema. @immutable class Address { final String? _line1; @@ -31,10 +35,10 @@ class Address { try { return _line1!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -48,10 +52,10 @@ class Address { try { return _city!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -61,10 +65,10 @@ class Address { try { return _state!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -74,10 +78,10 @@ class Address { try { return _postalCode!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -129,7 +133,7 @@ class Address { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Address {"); buffer.write("line1=" + "$_line1" + ", "); diff --git a/packages/amplify_test/lib/test_models/Blog.dart b/packages/amplify_test/lib/test_models/Blog.dart index 75e5f6d43b..f35e66de5e 100644 --- a/packages/amplify_test/lib/test_models/Blog.dart +++ b/packages/amplify_test/lib/test_models/Blog.dart @@ -17,18 +17,17 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'ModelProvider.dart'; import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type - -import 'ModelProvider.dart'; - -/** This is an auto generated class representing the Blog type in your schema. */ +/// This is an auto generated class representing the Blog type in your schema. @immutable class Blog extends Model { - static const classType = const _BlogModelType(); + static const classType = _BlogModelType(); final String id; final String? _name; final TemporalDateTime? _createdAt; @@ -40,16 +39,20 @@ class Blog extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + BlogModelIdentifier get modelIdentifier { + return BlogModelIdentifier(id: id); } String get name { try { return _name!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -130,7 +133,7 @@ class Blog extends Model { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Blog {"); buffer.write("id=" + "$id" + ", "); @@ -149,14 +152,13 @@ class Blog extends Model { } Blog copyWith( - {String? id, - String? name, + {String? name, TemporalDateTime? createdAt, S3Object? file, List? files, List? posts}) { return Blog._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, createdAt: createdAt ?? this.createdAt, file: file ?? this.file, @@ -172,20 +174,20 @@ class Blog extends Model { : null, _file = json['file']?['serializedData'] != null ? S3Object.fromJson( - new Map.from(json['file']['serializedData'])) + Map.from(json['file']['serializedData'])) : null, _files = json['files'] is List ? (json['files'] as List) .where((e) => e != null) .map((e) => S3Object.fromJson( - new Map.from(e['serializedData']))) + Map.from(e['serializedData']))) .toList() : null, _posts = json['posts'] is List ? (json['posts'] as List) .where((e) => e?['serializedData'] != null) .map((e) => Post.fromJson( - new Map.from(e['serializedData']))) + Map.from(e['serializedData']))) .toList() : null, _updatedAt = json['updatedAt'] != null @@ -202,6 +204,7 @@ class Blog extends Model { 'updatedAt': _updatedAt?.format() }; + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); static final QueryField ID = QueryField(fieldName: "blog.id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField CREATEDAT = QueryField(fieldName: "createdAt"); @@ -216,6 +219,10 @@ class Blog extends Model { modelSchemaDefinition.name = "Blog"; modelSchemaDefinition.pluralName = "Blogs"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id"], name: null) + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -263,3 +270,40 @@ class _BlogModelType extends ModelType { return Blog.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Blog] in your schema. +@immutable +class BlogModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of BlogModelIdentifier using [id] the primary key. + const BlogModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'BlogModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is BlogModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_test/lib/test_models/Comment.dart b/packages/amplify_test/lib/test_models/Comment.dart index 1ad3bcd56b..482080f33d 100644 --- a/packages/amplify_test/lib/test_models/Comment.dart +++ b/packages/amplify_test/lib/test_models/Comment.dart @@ -17,16 +17,16 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type import 'ModelProvider.dart'; import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the Comment type in your schema. */ +/// This is an auto generated class representing the Comment type in your schema. @immutable class Comment extends Model { - static const classType = const _CommentModelType(); + static const classType = _CommentModelType(); final String id; final Post? _post; final String? _content; @@ -36,9 +36,13 @@ class Comment extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + CommentModelIdentifier get modelIdentifier { + return CommentModelIdentifier(id: id); } Post? get post { @@ -49,7 +53,7 @@ class Comment extends Model { try { return _content!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -96,7 +100,7 @@ class Comment extends Model { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Comment {"); buffer.write("id=" + "$id" + ", "); @@ -112,18 +116,16 @@ class Comment extends Model { return buffer.toString(); } - Comment copyWith({String? id, Post? post, String? content}) { + Comment copyWith({Post? post, String? content}) { return Comment._internal( - id: id ?? this.id, - post: post ?? this.post, - content: content ?? this.content); + id: id, post: post ?? this.post, content: content ?? this.content); } Comment.fromJson(Map json) : id = json['id'], _post = json['post']?['serializedData'] != null ? Post.fromJson( - new Map.from(json['post']['serializedData'])) + Map.from(json['post']['serializedData'])) : null, _content = json['content'], _createdAt = json['createdAt'] != null @@ -141,6 +143,7 @@ class Comment extends Model { 'updatedAt': _updatedAt?.format() }; + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); static final QueryField ID = QueryField(fieldName: "comment.id"); static final QueryField POST = QueryField( fieldName: "post", @@ -152,6 +155,10 @@ class Comment extends Model { modelSchemaDefinition.name = "Comment"; modelSchemaDefinition.pluralName = "Comments"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["postID", "content"], name: "byPost") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( @@ -187,3 +194,40 @@ class _CommentModelType extends ModelType { return Comment.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Comment] in your schema. +@immutable +class CommentModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of CommentModelIdentifier using [id] the primary key. + const CommentModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'CommentModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CommentModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Contact.dart b/packages/amplify_test/lib/test_models/Contact.dart similarity index 72% rename from packages/amplify_datastore_plugin_interface/test/testData/Contact.dart rename to packages/amplify_test/lib/test_models/Contact.dart index e55bb5de93..9bfc6a6de6 100644 --- a/packages/amplify_datastore_plugin_interface/test/testData/Contact.dart +++ b/packages/amplify_test/lib/test_models/Contact.dart @@ -13,15 +13,18 @@ * permissions and limitations under the License. */ -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; -import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart'; +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the Contact type in your schema. */ +/// This is an auto generated class representing the Contact type in your schema. @immutable class Contact { final String? _email; @@ -32,10 +35,10 @@ class Contact { try { return _email!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -45,10 +48,10 @@ class Contact { try { return _phone!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -94,7 +97,7 @@ class Contact { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Contact {"); buffer.write("email=" + "$_email" + ", "); @@ -119,13 +122,13 @@ class Contact { : _email = json['email'], _phone = json['phone']?['serializedData'] != null ? Phone.fromJson( - new Map.from(json['phone']['serializedData'])) + Map.from(json['phone']['serializedData'])) : null, _mailingAddresses = json['mailingAddresses'] is List ? (json['mailingAddresses'] as List) .where((e) => e != null) .map((e) => Address.fromJson( - new Map.from(e['serializedData']))) + Map.from(e['serializedData']))) .toList() : null; diff --git a/packages/amplify_test/lib/test_models/FileMeta.dart b/packages/amplify_test/lib/test_models/FileMeta.dart index a55d750760..868f458969 100644 --- a/packages/amplify_test/lib/test_models/FileMeta.dart +++ b/packages/amplify_test/lib/test_models/FileMeta.dart @@ -13,12 +13,16 @@ * permissions and limitations under the License. */ -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the FileMeta type in your schema. */ +/// This is an auto generated class representing the FileMeta type in your schema. @immutable class FileMeta { final String? _name; @@ -27,7 +31,7 @@ class FileMeta { try { return _name!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -57,7 +61,7 @@ class FileMeta { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("FileMeta {"); buffer.write("name=" + "$_name"); diff --git a/packages/amplify_test/lib/test_models/Inventory.dart b/packages/amplify_test/lib/test_models/Inventory.dart new file mode 100644 index 0000000000..a3ee270b86 --- /dev/null +++ b/packages/amplify_test/lib/test_models/Inventory.dart @@ -0,0 +1,328 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the Inventory type in your schema. +@immutable +class Inventory extends Model { + static const classType = _InventoryModelType(); + final String? _productID; + final String? _name; + final String? _warehouseID; + final String? _region; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => modelIdentifier.serializeAsString(); + + InventoryModelIdentifier get modelIdentifier { + try { + return InventoryModelIdentifier( + productID: _productID!, + name: _name!, + warehouseID: _warehouseID!, + region: _region!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get productID { + try { + return _productID!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get warehouseID { + try { + return _warehouseID!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get region { + try { + return _region!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const Inventory._internal( + {required productID, + required name, + required warehouseID, + required region, + createdAt, + updatedAt}) + : _productID = productID, + _name = name, + _warehouseID = warehouseID, + _region = region, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory Inventory( + {required String productID, + required String name, + required String warehouseID, + required String region}) { + return Inventory._internal( + productID: productID, + name: name, + warehouseID: warehouseID, + region: region); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Inventory && + _productID == other._productID && + _name == other._name && + _warehouseID == other._warehouseID && + _region == other._region; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("Inventory {"); + buffer.write("productID=" + "$_productID" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("warehouseID=" + "$_warehouseID" + ", "); + buffer.write("region=" + "$_region" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + Inventory copyWith() { + return Inventory._internal( + productID: productID, + name: name, + warehouseID: warehouseID, + region: region); + } + + Inventory.fromJson(Map json) + : _productID = json['productID'], + _name = json['name'], + _warehouseID = json['warehouseID'], + _region = json['region'], + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'productID': _productID, + 'name': _name, + 'warehouseID': _warehouseID, + 'region': _region, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField PRODUCTID = QueryField(fieldName: "productID"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField WAREHOUSEID = QueryField(fieldName: "warehouseID"); + static final QueryField REGION = QueryField(fieldName: "region"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "Inventory"; + modelSchemaDefinition.pluralName = "Inventories"; + + modelSchemaDefinition.indexes = [ + ModelIndex( + fields: const ["productID", "name", "warehouseID", "region"], + name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Inventory.PRODUCTID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Inventory.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Inventory.WAREHOUSEID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Inventory.REGION, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _InventoryModelType extends ModelType { + const _InventoryModelType(); + + @override + Inventory fromJson(Map jsonData) { + return Inventory.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [Inventory] in your schema. +@immutable +class InventoryModelIdentifier implements ModelIdentifier { + final String productID; + final String name; + final String warehouseID; + final String region; + + /// Create an instance of InventoryModelIdentifier using [productID] the primary key. + /// And [name], [warehouseID], [region] the sort keys. + const InventoryModelIdentifier( + {required this.productID, + required this.name, + required this.warehouseID, + required this.region}); + + @override + Map serializeAsMap() => ({ + 'productID': productID, + 'name': name, + 'warehouseID': warehouseID, + 'region': region + }); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'InventoryModelIdentifier(productID: $productID, name: $name, warehouseID: $warehouseID, region: $region)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is InventoryModelIdentifier && + productID == other.productID && + name == other.name && + warehouseID == other.warehouseID && + region == other.region; + } + + @override + int get hashCode => + productID.hashCode ^ + name.hashCode ^ + warehouseID.hashCode ^ + region.hashCode; +} diff --git a/packages/amplify_test/lib/test_models/ModelProvider.dart b/packages/amplify_test/lib/test_models/ModelProvider.dart index 626da997f7..765ad08fd6 100644 --- a/packages/amplify_test/lib/test_models/ModelProvider.dart +++ b/packages/amplify_test/lib/test_models/ModelProvider.dart @@ -17,29 +17,63 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'package:amplify_core/amplify_core.dart'; import 'Blog.dart'; import 'Comment.dart'; +import 'Inventory.dart'; +import 'Person.dart'; import 'Post.dart'; +import 'PostWithAuthRules.dart'; +import 'Product.dart'; +import 'StringListTypeModel.dart'; +import 'Warehouse.dart'; +import 'Address.dart'; +import 'Contact.dart'; import 'FileMeta.dart'; +import 'Phone.dart'; import 'S3Object.dart'; +export 'Address.dart'; export 'Blog.dart'; export 'Comment.dart'; +export 'Contact.dart'; export 'FileMeta.dart'; +export 'Inventory.dart'; +export 'Person.dart'; +export 'Phone.dart'; export 'Post.dart'; +export 'PostWithAuthRules.dart'; +export 'Product.dart'; export 'S3Object.dart'; +export 'StringListTypeModel.dart'; +export 'Warehouse.dart'; class ModelProvider implements ModelProviderInterface { @override - String version = "e22227993ad5df5e265b0d065245b740"; + String version = "6c0a4ed8a5e5e532d6e91fe74ed634ea"; @override - List modelSchemas = [Blog.schema, Comment.schema, Post.schema]; + List modelSchemas = [ + Blog.schema, + Comment.schema, + Inventory.schema, + Person.schema, + Post.schema, + PostWithAuthRules.schema, + Product.schema, + StringListTypeModel.schema, + Warehouse.schema + ]; static final ModelProvider _instance = ModelProvider(); @override - List customTypeSchemas = [FileMeta.schema, S3Object.schema]; + List customTypeSchemas = [ + Address.schema, + Contact.schema, + FileMeta.schema, + Phone.schema, + S3Object.schema + ]; static ModelProvider get instance => _instance; @@ -49,8 +83,20 @@ class ModelProvider implements ModelProviderInterface { return Blog.classType; case "Comment": return Comment.classType; + case "Inventory": + return Inventory.classType; + case "Person": + return Person.classType; case "Post": return Post.classType; + case "PostWithAuthRules": + return PostWithAuthRules.classType; + case "Product": + return Product.classType; + case "StringListTypeModel": + return StringListTypeModel.classType; + case "Warehouse": + return Warehouse.classType; default: throw Exception( "Failed to find model in model provider for model name: " + diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Person.dart b/packages/amplify_test/lib/test_models/Person.dart similarity index 67% rename from packages/amplify_datastore_plugin_interface/test/testData/Person.dart rename to packages/amplify_test/lib/test_models/Person.dart index 74badaf7fe..5a61b4c38d 100644 --- a/packages/amplify_datastore_plugin_interface/test/testData/Person.dart +++ b/packages/amplify_test/lib/test_models/Person.dart @@ -13,17 +13,21 @@ * permissions and limitations under the License. */ -// ignore_for_file: public_member_api_docs +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the Person type in your schema. */ +/// This is an auto generated class representing the Person type in your schema. @immutable class Person extends Model { - static const classType = const _PersonModelType(); + static const classType = _PersonModelType(); final String id; final String? _name; final List
? _propertiesAddresses; @@ -34,19 +38,23 @@ class Person extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + PersonModelIdentifier get modelIdentifier { + return PersonModelIdentifier(id: id); } String get name { try { return _name!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -60,10 +68,10 @@ class Person extends Model { try { return _contact!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -124,7 +132,7 @@ class Person extends Model { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Person {"); buffer.write("id=" + "$id" + ", "); @@ -147,12 +155,9 @@ class Person extends Model { } Person copyWith( - {String? id, - String? name, - List
? propertiesAddresses, - Contact? contact}) { + {String? name, List
? propertiesAddresses, Contact? contact}) { return Person._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, propertiesAddresses: propertiesAddresses ?? this.propertiesAddresses, contact: contact ?? this.contact); @@ -165,12 +170,12 @@ class Person extends Model { ? (json['propertiesAddresses'] as List) .where((e) => e != null) .map((e) => Address.fromJson( - new Map.from(e['serializedData']))) + Map.from(e['serializedData']))) .toList() : null, _contact = json['contact']?['serializedData'] != null - ? Contact.fromJson(new Map.from( - json['contact']['serializedData'])) + ? Contact.fromJson( + Map.from(json['contact']['serializedData'])) : null, _createdAt = json['createdAt'] != null ? TemporalDateTime.fromString(json['createdAt']) @@ -189,6 +194,7 @@ class Person extends Model { 'updatedAt': _updatedAt?.format() }; + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); static final QueryField ID = QueryField(fieldName: "person.id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField PROPERTIESADDRESSES = @@ -241,3 +247,40 @@ class _PersonModelType extends ModelType { return Person.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Person] in your schema. +@immutable +class PersonModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of PersonModelIdentifier using [id] the primary key. + const PersonModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'PersonModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is PersonModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/Phone.dart b/packages/amplify_test/lib/test_models/Phone.dart similarity index 65% rename from packages/amplify_datastore_plugin_interface/test/testData/Phone.dart rename to packages/amplify_test/lib/test_models/Phone.dart index 2b80e2a80e..8f14363719 100644 --- a/packages/amplify_datastore_plugin_interface/test/testData/Phone.dart +++ b/packages/amplify_test/lib/test_models/Phone.dart @@ -13,12 +13,16 @@ * permissions and limitations under the License. */ -// ignore_for_file: public_member_api_docs +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the Phone type in your schema. */ +/// This is an auto generated class representing the Phone type in your schema. @immutable class Phone { final String? _country; @@ -28,10 +32,10 @@ class Phone { try { return _country!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -41,10 +45,10 @@ class Phone { try { return _number!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -75,7 +79,7 @@ class Phone { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Phone {"); buffer.write("country=" + "$_country" + ", "); diff --git a/packages/amplify_test/lib/test_models/Post.dart b/packages/amplify_test/lib/test_models/Post.dart index 3487b836a3..9477a3ac8e 100644 --- a/packages/amplify_test/lib/test_models/Post.dart +++ b/packages/amplify_test/lib/test_models/Post.dart @@ -17,21 +17,22 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type import 'ModelProvider.dart'; import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the Post type in your schema. */ +/// This is an auto generated class representing the Post type in your schema. @immutable class Post extends Model { - static const classType = const _PostModelType(); + static const classType = _PostModelType(); final String id; final String? _title; final int? _rating; final TemporalDateTime? _created; + final int? _likeCount; final Blog? _blog; final List? _comments; final TemporalDateTime? _createdAt; @@ -40,16 +41,20 @@ class Post extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + PostModelIdentifier get modelIdentifier { + return PostModelIdentifier(id: id); } String get title { try { return _title!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -62,7 +67,7 @@ class Post extends Model { try { return _rating!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -75,6 +80,10 @@ class Post extends Model { return _created; } + int? get likeCount { + return _likeCount; + } + Blog? get blog { return _blog; } @@ -96,6 +105,7 @@ class Post extends Model { required title, required rating, created, + likeCount, blog, comments, createdAt, @@ -103,6 +113,7 @@ class Post extends Model { : _title = title, _rating = rating, _created = created, + _likeCount = likeCount, _blog = blog, _comments = comments, _createdAt = createdAt, @@ -113,6 +124,7 @@ class Post extends Model { required String title, required int rating, TemporalDateTime? created, + int? likeCount, Blog? blog, List? comments}) { return Post._internal( @@ -120,6 +132,7 @@ class Post extends Model { title: title, rating: rating, created: created, + likeCount: likeCount, blog: blog, comments: comments != null ? List.unmodifiable(comments) : comments); @@ -137,6 +150,7 @@ class Post extends Model { _title == other._title && _rating == other._rating && _created == other._created && + _likeCount == other._likeCount && _blog == other._blog && DeepCollectionEquality().equals(_comments, other._comments); } @@ -146,7 +160,7 @@ class Post extends Model { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("Post {"); buffer.write("id=" + "$id" + ", "); @@ -155,6 +169,9 @@ class Post extends Model { "rating=" + (_rating != null ? _rating!.toString() : "null") + ", "); buffer.write( "created=" + (_created != null ? _created!.format() : "null") + ", "); + buffer.write("likeCount=" + + (_likeCount != null ? _likeCount!.toString() : "null") + + ", "); buffer.write("blog=" + (_blog != null ? _blog!.toString() : "null") + ", "); buffer.write("createdAt=" + (_createdAt != null ? _createdAt!.format() : "null") + @@ -167,17 +184,18 @@ class Post extends Model { } Post copyWith( - {String? id, - String? title, + {String? title, int? rating, TemporalDateTime? created, + int? likeCount, Blog? blog, List? comments}) { return Post._internal( - id: id ?? this.id, + id: id, title: title ?? this.title, rating: rating ?? this.rating, created: created ?? this.created, + likeCount: likeCount ?? this.likeCount, blog: blog ?? this.blog, comments: comments ?? this.comments); } @@ -189,15 +207,16 @@ class Post extends Model { _created = json['created'] != null ? TemporalDateTime.fromString(json['created']) : null, + _likeCount = (json['likeCount'] as num?)?.toInt(), _blog = json['blog']?['serializedData'] != null ? Blog.fromJson( - new Map.from(json['blog']['serializedData'])) + Map.from(json['blog']['serializedData'])) : null, _comments = json['comments'] is List ? (json['comments'] as List) .where((e) => e?['serializedData'] != null) .map((e) => Comment.fromJson( - new Map.from(e['serializedData']))) + Map.from(e['serializedData']))) .toList() : null, _createdAt = json['createdAt'] != null @@ -212,16 +231,19 @@ class Post extends Model { 'title': _title, 'rating': _rating, 'created': _created?.format(), + 'likeCount': _likeCount, 'blog': _blog?.toJson(), 'comments': _comments?.map((Comment? e) => e?.toJson()).toList(), 'createdAt': _createdAt?.format(), 'updatedAt': _updatedAt?.format() }; + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); static final QueryField ID = QueryField(fieldName: "post.id"); static final QueryField TITLE = QueryField(fieldName: "title"); static final QueryField RATING = QueryField(fieldName: "rating"); static final QueryField CREATED = QueryField(fieldName: "created"); + static final QueryField LIKECOUNT = QueryField(fieldName: "likeCount"); static final QueryField BLOG = QueryField( fieldName: "blog", fieldType: ModelFieldType(ModelFieldTypeEnum.model, @@ -235,6 +257,10 @@ class Post extends Model { modelSchemaDefinition.name = "Post"; modelSchemaDefinition.pluralName = "Posts"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["blogID"], name: "byBlog") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -252,6 +278,11 @@ class Post extends Model { isRequired: false, ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.LIKECOUNT, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.int))); + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: Post.BLOG, isRequired: false, @@ -286,3 +317,40 @@ class _PostModelType extends ModelType { return Post.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Post] in your schema. +@immutable +class PostModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of PostModelIdentifier using [id] the primary key. + const PostModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'PostModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is PostModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore_plugin_interface/test/testData/PostAuthComplex.dart b/packages/amplify_test/lib/test_models/PostWithAuthRules.dart similarity index 51% rename from packages/amplify_datastore_plugin_interface/test/testData/PostAuthComplex.dart rename to packages/amplify_test/lib/test_models/PostWithAuthRules.dart index 51d41060a5..7e31d2f36a 100644 --- a/packages/amplify_datastore_plugin_interface/test/testData/PostAuthComplex.dart +++ b/packages/amplify_test/lib/test_models/PostWithAuthRules.dart @@ -13,15 +13,19 @@ * permissions and limitations under the License. */ -// ignore_for_file: public_member_api_docs +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the PostAuthComplex type in your schema. */ +/// This is an auto generated class representing the PostWithAuthRules type in your schema. @immutable -class PostAuthComplex extends Model { - static const classType = const _PostAuthComplexModelType(); +class PostWithAuthRules extends Model { + static const classType = _PostWithAuthRulesModelType(); final String id; final String? _title; final String? _owner; @@ -31,19 +35,23 @@ class PostAuthComplex extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + PostWithAuthRulesModelIdentifier get modelIdentifier { + return PostWithAuthRulesModelIdentifier(id: id); } String get title { try { return _title!; } catch (e) { - throw new DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -61,15 +69,16 @@ class PostAuthComplex extends Model { return _updatedAt; } - const PostAuthComplex._internal( + const PostWithAuthRules._internal( {required this.id, required title, owner, createdAt, updatedAt}) : _title = title, _owner = owner, _createdAt = createdAt, _updatedAt = updatedAt; - factory PostAuthComplex({String? id, required String title, String? owner}) { - return PostAuthComplex._internal( + factory PostWithAuthRules( + {String? id, required String title, String? owner}) { + return PostWithAuthRules._internal( id: id == null ? UUID.getUUID() : id, title: title, owner: owner); } @@ -80,7 +89,7 @@ class PostAuthComplex extends Model { @override bool operator ==(Object other) { if (identical(other, this)) return true; - return other is PostAuthComplex && + return other is PostWithAuthRules && id == other.id && _title == other._title && _owner == other._owner; @@ -91,9 +100,9 @@ class PostAuthComplex extends Model { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); - buffer.write("PostAuthComplex {"); + buffer.write("PostWithAuthRules {"); buffer.write("id=" + "$id" + ", "); buffer.write("title=" + "$_title" + ", "); buffer.write("owner=" + "$_owner" + ", "); @@ -107,14 +116,12 @@ class PostAuthComplex extends Model { return buffer.toString(); } - PostAuthComplex copyWith({String? id, String? title, String? owner}) { - return PostAuthComplex._internal( - id: id ?? this.id, - title: title ?? this.title, - owner: owner ?? this.owner); + PostWithAuthRules copyWith({String? title, String? owner}) { + return PostWithAuthRules._internal( + id: id, title: title ?? this.title, owner: owner ?? this.owner); } - PostAuthComplex.fromJson(Map json) + PostWithAuthRules.fromJson(Map json) : id = json['id'], _title = json['title'], _owner = json['owner'], @@ -133,19 +140,21 @@ class PostAuthComplex extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "postAuthComplex.id"); + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "postWithAuthRules.id"); static final QueryField TITLE = QueryField(fieldName: "title"); static final QueryField OWNER = QueryField(fieldName: "owner"); static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { - modelSchemaDefinition.name = "PostAuthComplex"; - modelSchemaDefinition.pluralName = "PostAuthComplexes"; + modelSchemaDefinition.name = "PostWithAuthRules"; + modelSchemaDefinition.pluralName = "PostWithAuthRules"; modelSchemaDefinition.authRules = [ AuthRule( authStrategy: AuthStrategy.OWNER, ownerField: "owner", identityClaim: "cognito:username", + provider: AuthRuleProvider.USERPOOLS, operations: [ ModelOperation.CREATE, ModelOperation.UPDATE, @@ -157,12 +166,12 @@ class PostAuthComplex extends Model { modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: PostAuthComplex.TITLE, + key: PostWithAuthRules.TITLE, isRequired: true, ofType: ModelFieldType(ModelFieldTypeEnum.string))); modelSchemaDefinition.addField(ModelFieldDefinition.field( - key: PostAuthComplex.OWNER, + key: PostWithAuthRules.OWNER, isRequired: false, ofType: ModelFieldType(ModelFieldTypeEnum.string))); @@ -180,11 +189,49 @@ class PostAuthComplex extends Model { }); } -class _PostAuthComplexModelType extends ModelType { - const _PostAuthComplexModelType(); +class _PostWithAuthRulesModelType extends ModelType { + const _PostWithAuthRulesModelType(); @override - PostAuthComplex fromJson(Map jsonData) { - return PostAuthComplex.fromJson(jsonData); + PostWithAuthRules fromJson(Map jsonData) { + return PostWithAuthRules.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [PostWithAuthRules] in your schema. +@immutable +class PostWithAuthRulesModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of PostWithAuthRulesModelIdentifier using [id] the primary key. + const PostWithAuthRulesModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'PostWithAuthRulesModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is PostWithAuthRulesModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_test/lib/test_models/Product.dart b/packages/amplify_test/lib/test_models/Product.dart new file mode 100644 index 0000000000..7e99c99fcb --- /dev/null +++ b/packages/amplify_test/lib/test_models/Product.dart @@ -0,0 +1,268 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the Product type in your schema. +@immutable +class Product extends Model { + static const classType = _ProductModelType(); + final String? _productID; + final String? _name; + final int? _amount; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => modelIdentifier.serializeAsString(); + + ProductModelIdentifier get modelIdentifier { + try { + return ProductModelIdentifier(productID: _productID!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get productID { + try { + return _productID!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + int get amount { + try { + return _amount!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const Product._internal( + {required productID, + required name, + required amount, + createdAt, + updatedAt}) + : _productID = productID, + _name = name, + _amount = amount, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory Product( + {required String productID, required String name, required int amount}) { + return Product._internal(productID: productID, name: name, amount: amount); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Product && + _productID == other._productID && + _name == other._name && + _amount == other._amount; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("Product {"); + buffer.write("productID=" + "$_productID" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write( + "amount=" + (_amount != null ? _amount!.toString() : "null") + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + Product copyWith({String? name, int? amount}) { + return Product._internal( + productID: productID, + name: name ?? this.name, + amount: amount ?? this.amount); + } + + Product.fromJson(Map json) + : _productID = json['productID'], + _name = json['name'], + _amount = (json['amount'] as num?)?.toInt(), + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'productID': _productID, + 'name': _name, + 'amount': _amount, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField PRODUCTID = QueryField(fieldName: "productID"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField AMOUNT = QueryField(fieldName: "amount"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "Product"; + modelSchemaDefinition.pluralName = "Products"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["productID"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Product.PRODUCTID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Product.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Product.AMOUNT, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.int))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _ProductModelType extends ModelType { + const _ProductModelType(); + + @override + Product fromJson(Map jsonData) { + return Product.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [Product] in your schema. +@immutable +class ProductModelIdentifier implements ModelIdentifier { + final String productID; + + /// Create an instance of ProductModelIdentifier using [productID] the primary key. + const ProductModelIdentifier({required this.productID}); + + @override + Map serializeAsMap() => + ({'productID': productID}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'ProductModelIdentifier(productID: $productID)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is ProductModelIdentifier && productID == other.productID; + } + + @override + int get hashCode => productID.hashCode; +} diff --git a/packages/amplify_test/lib/test_models/S3Object.dart b/packages/amplify_test/lib/test_models/S3Object.dart index 774a357c11..51e4a52a4b 100644 --- a/packages/amplify_test/lib/test_models/S3Object.dart +++ b/packages/amplify_test/lib/test_models/S3Object.dart @@ -13,13 +13,17 @@ * permissions and limitations under the License. */ -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type import 'ModelProvider.dart'; import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; -/** This is an auto generated class representing the S3Object type in your schema. */ +/// This is an auto generated class representing the S3Object type in your schema. @immutable class S3Object { final String? _bucket; @@ -31,7 +35,7 @@ class S3Object { try { return _bucket!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -44,7 +48,7 @@ class S3Object { try { return _region!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -57,7 +61,7 @@ class S3Object { try { return _key!; } catch (e) { - throw new AmplifyCodeGenModelException( + throw AmplifyCodeGenModelException( AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: AmplifyExceptionMessages @@ -105,7 +109,7 @@ class S3Object { @override String toString() { - var buffer = new StringBuffer(); + var buffer = StringBuffer(); buffer.write("S3Object {"); buffer.write("bucket=" + "$_bucket" + ", "); @@ -132,7 +136,7 @@ class S3Object { _key = json['key'], _meta = json['meta']?['serializedData'] != null ? FileMeta.fromJson( - new Map.from(json['meta']['serializedData'])) + Map.from(json['meta']['serializedData'])) : null; Map toJson() => { diff --git a/packages/amplify_test/lib/test_models/StringListTypeModel.dart b/packages/amplify_test/lib/test_models/StringListTypeModel.dart new file mode 100644 index 0000000000..651b6ea010 --- /dev/null +++ b/packages/amplify_test/lib/test_models/StringListTypeModel.dart @@ -0,0 +1,201 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the StringListTypeModel type in your schema. +@immutable +class StringListTypeModel extends Model { + static const classType = _StringListTypeModelModelType(); + final String id; + final List? _value; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + StringListTypeModelModelIdentifier get modelIdentifier { + return StringListTypeModelModelIdentifier(id: id); + } + + List? get value { + return _value; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const StringListTypeModel._internal( + {required this.id, value, createdAt, updatedAt}) + : _value = value, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory StringListTypeModel({String? id, List? value}) { + return StringListTypeModel._internal( + id: id == null ? UUID.getUUID() : id, + value: value != null ? List.unmodifiable(value) : value); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is StringListTypeModel && + id == other.id && + DeepCollectionEquality().equals(_value, other._value); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("StringListTypeModel {"); + buffer.write("id=" + "$id" + ", "); + buffer.write( + "value=" + (_value != null ? _value!.toString() : "null") + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + StringListTypeModel copyWith({List? value}) { + return StringListTypeModel._internal(id: id, value: value ?? this.value); + } + + StringListTypeModel.fromJson(Map json) + : id = json['id'], + _value = json['value']?.cast(), + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'value': _value, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "stringListTypeModel.id"); + static final QueryField VALUE = QueryField(fieldName: "value"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "StringListTypeModel"; + modelSchemaDefinition.pluralName = "StringListTypeModels"; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: StringListTypeModel.VALUE, + isRequired: false, + isArray: true, + ofType: ModelFieldType(ModelFieldTypeEnum.collection, + ofModelName: describeEnum(ModelFieldTypeEnum.string)))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _StringListTypeModelModelType extends ModelType { + const _StringListTypeModelModelType(); + + @override + StringListTypeModel fromJson(Map jsonData) { + return StringListTypeModel.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [StringListTypeModel] in your schema. +@immutable +class StringListTypeModelModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of StringListTypeModelModelIdentifier using [id] the primary key. + const StringListTypeModelModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'StringListTypeModelModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is StringListTypeModelModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_test/lib/test_models/Warehouse.dart b/packages/amplify_test/lib/test_models/Warehouse.dart new file mode 100644 index 0000000000..1e9d46b334 --- /dev/null +++ b/packages/amplify_test/lib/test_models/Warehouse.dart @@ -0,0 +1,252 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously, implicit_dynamic_parameter, implicit_dynamic_map_literal, implicit_dynamic_type + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the Warehouse type in your schema. +@immutable +class Warehouse extends Model { + static const classType = _WarehouseModelType(); + final String id; + final String? _name; + final String? _region; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + WarehouseModelIdentifier get modelIdentifier { + try { + return WarehouseModelIdentifier(id: id, name: _name!, region: _region!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get region { + try { + return _region!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const Warehouse._internal( + {required this.id, required name, required region, createdAt, updatedAt}) + : _name = name, + _region = region, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory Warehouse( + {String? id, required String name, required String region}) { + return Warehouse._internal( + id: id == null ? UUID.getUUID() : id, name: name, region: region); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Warehouse && + id == other.id && + _name == other._name && + _region == other._region; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("Warehouse {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("region=" + "$_region" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + Warehouse copyWith() { + return Warehouse._internal(id: id, name: name, region: region); + } + + Warehouse.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _region = json['region'], + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'region': _region, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "warehouse.id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField REGION = QueryField(fieldName: "region"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "Warehouse"; + modelSchemaDefinition.pluralName = "Warehouses"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name", "region"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Warehouse.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Warehouse.REGION, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _WarehouseModelType extends ModelType { + const _WarehouseModelType(); + + @override + Warehouse fromJson(Map jsonData) { + return Warehouse.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [Warehouse] in your schema. +@immutable +class WarehouseModelIdentifier implements ModelIdentifier { + final String id; + final String name; + final String region; + + /// Create an instance of WarehouseModelIdentifier using [id] the primary key. + /// And [name], [region] the sort keys. + const WarehouseModelIdentifier( + {required this.id, required this.name, required this.region}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name, 'region': region}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'WarehouseModelIdentifier(id: $id, name: $name, region: $region)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is WarehouseModelIdentifier && + id == other.id && + name == other.name && + region == other.region; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode ^ region.hashCode; +} diff --git a/packages/amplify_test/lib/test_models/schema.graphql b/packages/amplify_test/lib/test_models/schema.graphql new file mode 100644 index 0000000000..874cdd9beb --- /dev/null +++ b/packages/amplify_test/lib/test_models/schema.graphql @@ -0,0 +1,108 @@ +input AMPLIFY { + globalAuthRule: AuthRule = { allow: public } +} + +type FileMeta { + name: String! +} + +type S3Object { + bucket: String! + region: String! + key: String! + meta: FileMeta +} + +type Blog @model { + id: ID! @primaryKey + name: String! + createdAt: AWSDateTime + file: S3Object + files: [S3Object] + posts: [Post] @hasMany(indexName: "byBlog", fields: ["id"]) +} + +type Post @model { + id: ID! + title: String! + rating: Int! + created: AWSDateTime + likeCount: Int + blogID: ID! @index(name: "byBlog") + blog: Blog @belongsTo(fields: ["blogID"]) + comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"]) +} + +type Comment @model { + id: ID! + postID: ID! @index(name: "byPost", sortKeyFields: ["content"]) + post: Post @belongsTo(fields: ["postID"]) + content: String! +} + +type PostWithAuthRules + @model + @auth( + rules: [ + { + allow: owner + ownerField: "owner" + operations: [create, update, delete, read] + } + ] + ) { + id: ID! + title: String! + owner: String +} + +type Address { + line1: String! + line2: String + city: String! + state: String! + postalCode: String! +} + +type Person @model { + id: ID! + name: String! + propertiesAddresses: [Address] + contact: Contact! +} + +type Phone { + country: String! + number: String! +} + +type Contact { + email: String! + phone: Phone! + mailingAddresses: [Address] +} + +type Product @model { + productID: ID! @primaryKey + name: String! + amount: Int! +} + +type Inventory @model { + productID: String! + @primaryKey(sortKeyFields: ["name", "warehouseID", "region"]) + name: String! + warehouseID: ID! + region: String! +} + +type Warehouse @model { + id: ID! @primaryKey(sortKeyFields: ["name", "region"]) + name: String! + region: String! +} + +type StringListTypeModel @model { + id: ID! + value: [String] +} diff --git a/packages/api/amplify_api/test/graphql_helpers_test.dart b/packages/api/amplify_api/test/graphql_helpers_test.dart index c32e3f44e9..559420a2c6 100644 --- a/packages/api/amplify_api/test/graphql_helpers_test.dart +++ b/packages/api/amplify_api/test/graphql_helpers_test.dart @@ -383,11 +383,12 @@ void main() { 'title': title, 'rating': rating, 'created': null, + 'likeCount': null, 'blogID': blogId } }; const expectedDoc = - 'mutation createPost(\$input: CreatePostInput!, \$condition: ModelPostConditionInput) { createPost(input: \$input, condition: \$condition) { id title rating created createdAt updatedAt blog { $blogSelectionSet } } }'; + 'mutation createPost(\$input: CreatePostInput!, \$condition: ModelPostConditionInput) { createPost(input: \$input, condition: \$condition) { id title rating created likeCount createdAt updatedAt blog { $blogSelectionSet } } }'; GraphQLRequest req = ModelMutations.create(post); expect(req.document, expectedDoc); @@ -498,12 +499,13 @@ void main() { 'title': title, 'rating': rating, 'created': null, + 'likeCount': null, 'blogID': blogId }, 'condition': null }; const expectedDoc = - 'mutation updatePost(\$input: UpdatePostInput!, \$condition: ModelPostConditionInput) { updatePost(input: \$input, condition: \$condition) { id title rating created createdAt updatedAt blog { $blogSelectionSet } } }'; + 'mutation updatePost(\$input: UpdatePostInput!, \$condition: ModelPostConditionInput) { updatePost(input: \$input, condition: \$condition) { id title rating created likeCount createdAt updatedAt blog { $blogSelectionSet } } }'; GraphQLRequest req = ModelMutations.update(post); expect(req.document, expectedDoc); From 5e49a29d20bbe7092b675b60906272b87d644c07 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 25 May 2022 13:16:43 -0700 Subject: [PATCH 05/10] chore(datastore): unit tests for custom primary key native imp. --- .../AmplifyDataStoreHubTest.kt | 9 +- .../AmplifyDataStorePluginTest.kt | 29 +-- .../AmplifyModelSchemaTest.kt | 13 ++ .../FlutterSerializedModelData.kt | 22 ++- .../amplify/amplify_datastore/SchemaData.kt | 181 +++++++++++++++++- .../types/query/QueryPredicateBuilderTest.kt | 110 ++++++++++- .../ios/Runner.xcodeproj/project.pbxproj | 20 ++ .../AmplifyModelSchemaUnitTests.swift | 15 +- .../AmplifySerializedModelUnitTests.swift | 17 -- .../DataStoreHubEventStreamHandlerTests.swift | 8 +- .../unit_tests/DataStorePluginUnitTests.swift | 16 +- .../QueryPredicateBuilderUnitTests.swift | 63 ++++++ .../FlutterSerializedModelData.swift | 20 +- .../ios/unit_tests/resources/SchemaData.swift | 49 +++-- .../modelSchema/model_schema_maps.json | 54 ++++++ .../modelSchema/serialized_model_maps.json | 5 - .../predicates/model_identifier_equals.json | 19 ++ .../model_identifier_group_equals.json | 26 +++ .../model_identifier_group_not_equals.json | 26 +++ .../model_identifier_not_equals.json | 19 ++ .../relation_model_identifier_equals.json | 16 ++ .../model_schema/model_schema_maps.json | 59 ++++++ .../model_schema/serialized_model_maps.json | 5 - .../observe_api/blog_type_success_event.json | 1 - .../observe_api/post_type_success_event.json | 1 - .../query_api/response/2_results.json | 2 - .../query_api/response/nested_results.json | 1 - .../query_by_nested_model_identifier.json | 12 ++ .../amplify/amplify_api/AuthProviderTests.kt | 1 - 29 files changed, 712 insertions(+), 107 deletions(-) create mode 100644 packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_equals.json create mode 100644 packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_equals.json create mode 100644 packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_not_equals.json create mode 100644 packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_not_equals.json create mode 100644 packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/relation_model_identifier_equals.json create mode 100644 packages/amplify_datastore/test/resources/query_predicate/query_by_nested_model_identifier.json diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt index 351c6b6a96..22987af47d 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStoreHubTest.kt @@ -94,15 +94,15 @@ class AmplifyDataStoreHubTest { var metadataMap: HashMap val modelMap: HashMap = element["model"] as HashMap val serializedData: HashMap = modelMap["serializedData"] as HashMap - val modelMetadata = ModelMetadata(modelMap["id"] as String, null, null, null) + val modelMetadata = ModelMetadata(modelMap["id"] as String, null, null, null, "Post") val modelData = mapOf( "id" to serializedData["id"] as String, "title" to serializedData["title"] as String, "created" to Temporal.DateTime(serializedData["created"] as String) ) val instance = SerializedModel.builder() - .serializedData(modelData) .modelSchema(modelSchema) + .serializedData(modelData) .build() val modelWithMetadata: ModelWithMetadata = ModelWithMetadata(instance, modelMetadata) @@ -147,7 +147,8 @@ class AmplifyDataStoreHubTest { metadataMap["id"] as String, metadataMap["_deleted"] as Boolean, metadataMap["_version"] as Int, - time + time, + "Post" ) val modelData = mapOf( "id" to serializedData["id"] as String, @@ -155,8 +156,8 @@ class AmplifyDataStoreHubTest { "created" to Temporal.DateTime(serializedData["created"] as String) ) val instance = SerializedModel.builder() - .serializedData(modelData) .modelSchema(modelSchema) + .serializedData(modelData) .build() val modelWithMetadata: ModelWithMetadata = ModelWithMetadata(instance, modelMetadata) diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt index 2bc3a56128..535ee6efc4 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyDataStorePluginTest.kt @@ -115,6 +115,7 @@ class AmplifyDataStorePluginTest { modelSchema = flutterPlugin.modelProvider.modelSchemas()["Post"]!! amplifySuccessResults = mutableListOf( SerializedModel.builder() + .modelSchema(modelSchema) .serializedData( mapOf( "id" to "4281dfba-96c8-4a38-9a8e-35c7e893ea47", @@ -123,9 +124,9 @@ class AmplifyDataStorePluginTest { "created" to Temporal.DateTime("2020-02-20T20:20:20+03:50") ) ) - .modelSchema(modelSchema) .build(), SerializedModel.builder() + .modelSchema(modelSchema) .serializedData( mapOf( "id" to "43036c6b-8044-4309-bddc-262b6c686026", @@ -136,7 +137,6 @@ class AmplifyDataStorePluginTest { ) ) ) - .modelSchema(modelSchema) .build() ) setFinalStatic(Amplify::class.java.getDeclaredField("DataStore"), mockDataStore) @@ -408,8 +408,8 @@ class AmplifyDataStorePluginTest { testRequest["serializedModel"] as HashMap val serializedModel = SerializedModel.builder() - .serializedData(serializedModelData) .modelSchema(modelSchema) + .serializedData(serializedModelData) .build() val dataStoreItemChange = DataStoreItemChange.builder() @@ -452,8 +452,8 @@ class AmplifyDataStorePluginTest { testRequest["serializedModel"] as HashMap val serializedModel = SerializedModel.builder() - .serializedData(serializedModelData) .modelSchema(modelSchema) + .serializedData(serializedModelData) .build() doAnswer { invocation: InvocationOnMock -> @@ -513,8 +513,8 @@ class AmplifyDataStorePluginTest { testRequest["serializedModel"] as HashMap val serializedModel = SerializedModel.builder() - .serializedData(serializedModelData) .modelSchema(modelSchema) + .serializedData(serializedModelData) .build() val dataStoreItemChange = DataStoreItemChange.builder() @@ -558,8 +558,8 @@ class AmplifyDataStorePluginTest { testRequest["serializedModel"] as HashMap val serializedModel = SerializedModel.builder() - .serializedData(serializedModelData) .modelSchema(modelSchema) + .serializedData(serializedModelData) .build() doAnswer { invocation: InvocationOnMock -> @@ -674,8 +674,8 @@ class AmplifyDataStorePluginTest { "created" to Temporal.DateTime("2020-02-20T20:20:20-08:00") ) val instance = SerializedModel.builder() - .serializedData(modelData) .modelSchema(modelSchema) + .serializedData(modelData) .build() val dataStoreItemChange = DataStoreItemChange.builder() @@ -790,12 +790,15 @@ class AmplifyDataStorePluginTest { "id" to "af9cfa64-1ea9-46d6-b9e2-8203179d5392", "title" to "A brilliant Post", "rating" to 5, - "blog" to SerializedModel.builder().serializedData( - mapOf( - "name" to "Amazing Blog", - "id" to "8cb7d5a5-435d-4632-a890-90ed0c6107f5" - ) as HashMap - ).modelSchema(blogModelSchema).build() + "blog" to SerializedModel.builder() + .modelSchema(blogModelSchema) + .serializedData( + mapOf( + "name" to "Amazing Blog", + "id" to "8cb7d5a5-435d-4632-a890-90ed0c6107f5" + ) as HashMap + ) + .build() ) assertEquals( diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt index b0ac982acf..ba1e3e33d2 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/AmplifyModelSchemaTest.kt @@ -128,4 +128,17 @@ class AmplifyModelSchemaTest { personSchema ) } + + @Test + fun test_custom_primary_key_model_schema() { + val inputMap = schemasMap["InventoryModelSchema"] as Map + val modelSchema = FlutterModelSchema(inputMap) + val convertedModelSchema = modelSchema.convertToNativeModelSchema() + + // Verify result + assertEquals( + convertedModelSchema, + inventorySchema + ) + } } diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/FlutterSerializedModelData.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/FlutterSerializedModelData.kt index 157524cb7e..09ee94cbde 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/FlutterSerializedModelData.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/FlutterSerializedModelData.kt @@ -19,16 +19,20 @@ import com.amplifyframework.core.model.SerializedCustomType import com.amplifyframework.core.model.SerializedModel val blogSerializedModel = SerializedModel.builder() + .modelSchema( + blogSchema + ) .serializedData( mapOf( "id" to "999", "name" to "blog name" ) - ).modelSchema( - blogSchema ).build() var commentSerializedModel = SerializedModel.builder() + .modelSchema( + commentSchema + ) .serializedData( mapOf( "id" to "999", @@ -37,11 +41,12 @@ var commentSerializedModel = SerializedModel.builder() ), "content" to "content" ) - ).modelSchema( - commentSchema ).build() var postSerializedModel = SerializedModel.builder() + .modelSchema( + postSchema + ) .serializedData( mapOf( "id" to "999", @@ -51,11 +56,12 @@ var postSerializedModel = SerializedModel.builder() "id" to "555" ) ) - ).modelSchema( - postSchema ).build() var allTypeModelSerializedModel = SerializedModel.builder() + .modelSchema( + allTypeModelSchema + ) .serializedData( mapOf( "id" to "999", @@ -69,11 +75,10 @@ var allTypeModelSerializedModel = SerializedModel.builder() "timestampType" to 999, "enumType" to "maybe" ) - ).modelSchema( - allTypeModelSchema ).build() val personSerializedModel = SerializedModel.builder() + .modelSchema(personSchema) .serializedData( mapOf( "id" to "123", @@ -138,5 +143,4 @@ val personSerializedModel = SerializedModel.builder() ) ) ) - .modelSchema(personSchema) .build() diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt index 1ad243afd1..320d8290ff 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/SchemaData.kt @@ -22,6 +22,7 @@ import com.amplifyframework.core.model.CustomTypeSchema import com.amplifyframework.core.model.Model import com.amplifyframework.core.model.ModelAssociation import com.amplifyframework.core.model.ModelField +import com.amplifyframework.core.model.ModelIndex import com.amplifyframework.core.model.ModelSchema import com.amplifyframework.core.model.SerializedModel import com.amplifyframework.core.model.temporal.Temporal @@ -29,6 +30,12 @@ import com.amplifyframework.core.model.temporal.Temporal val postSchema = ModelSchema.builder() .name("Post") .pluralName("Posts") + .indexes(mapOf( + "byBlog" to ModelIndex.builder() + .indexName("byBlog") + .indexFieldNames(listOf("blogID")) + .build() + )) .fields( mapOf( "id" to @@ -120,7 +127,7 @@ val postSchema = ModelSchema.builder() "blog" to ModelAssociation.builder() .name("BelongsTo") - .targetName("blogID") + .targetNames(listOf("blogID").toTypedArray()) .build(), "comments" to ModelAssociation.builder() @@ -132,6 +139,7 @@ val postSchema = ModelSchema.builder() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val postAuthComplexSchema = ModelSchema.builder() @@ -205,6 +213,7 @@ val postAuthComplexSchema = ModelSchema.builder() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val postAuthComplexWithProviderUserPoolsSchema = ModelSchema.builder() @@ -260,6 +269,7 @@ val postAuthComplexWithProviderUserPoolsSchema = ModelSchema.builder() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val postAuthComplexWithProviderApiKeySchema = ModelSchema.builder() @@ -305,6 +315,7 @@ val postAuthComplexWithProviderApiKeySchema = ModelSchema.builder() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val commentSchema = ModelSchema.builder() @@ -363,11 +374,12 @@ val commentSchema = ModelSchema.builder() "post" to ModelAssociation.builder() .name("BelongsTo") - .targetName("postID") + .targetNames(listOf("postID").toTypedArray()) .build() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val blogSchema = ModelSchema.builder() @@ -431,6 +443,7 @@ val blogSchema = ModelSchema.builder() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val allTypeModelSchema = ModelSchema.builder() @@ -540,6 +553,7 @@ val allTypeModelSchema = ModelSchema.builder() ) ) .modelClass(SerializedModel::class.java) + .version(1) .build() val phoneSchema = CustomTypeSchema.builder() @@ -682,4 +696,167 @@ val personSchema = ModelSchema.builder() .build() ) ) + .version(1) + .build() + +val inventorySchema = ModelSchema.builder() + .name("Inventory") + .pluralName("Inventories") + .modelClass(SerializedModel::class.java) + .indexes(mapOf( + "undefined" to ModelIndex.builder() + .indexName("undefined") + .indexFieldNames(listOf("productID", "name", "warehouseID", "region")) + .build() + )) + .fields(mapOf( + "productID" to ModelField.builder() + .name("productID") + .targetType("String") + .javaClassForValue(String::class.java) + .isRequired(true) + .isReadOnly(false) + .isArray(false) + .build(), + "name" to ModelField.builder() + .name("name") + .targetType("String") + .javaClassForValue(String::class.java) + .isRequired(true) + .isReadOnly(false) + .isArray(false) + .build(), + "warehouseID" to ModelField.builder() + .name("warehouseID") + .targetType("String") + .javaClassForValue(String::class.java) + .isRequired(true) + .isReadOnly(false) + .isArray(false) + .build(), + "region" to ModelField.builder() + .name("region") + .targetType("String") + .javaClassForValue(String::class.java) + .isRequired(true) + .isReadOnly(false) + .isArray(false) + .build() + )) + .version(1) + .build() + +val cpkPostSchema = ModelSchema.builder() + .name("Post") + .pluralName("Posts") + .indexes(mapOf( + "byBlog" to ModelIndex.builder() + .indexName("byBlog") + .indexFieldNames(listOf("blogID")) + .build() + )) + .fields( + mapOf( + "id" to + ModelField.builder() + .name("id") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), + "title" to + ModelField.builder() + .name("title") + .javaClassForValue(String::class.java) + .targetType("String") + .isRequired(true) + .isArray(false) + .build(), + + "created" to + ModelField.builder() + .name("created") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .build(), + + "rating" to + ModelField.builder() + .name("rating") + .javaClassForValue(Integer::class.java) + .targetType("Integer") + .isRequired(false) + .isArray(false) + .build(), + + "blog" to + ModelField.builder() + .name("blog") + .javaClassForValue(Model::class.java) + .targetType("Blog") + .isRequired(false) + .isArray(false) + .isModel(true) + .build(), + + "comments" to + ModelField.builder() + .name("comments") + .javaClassForValue(List::class.java) + .targetType("Comment") + .isRequired(false) + .isArray(true) + .build(), + + "likeCount" to + ModelField.builder() + .name("likeCount") + .javaClassForValue(Integer::class.java) + .targetType("Integer") + .isRequired(false) + .isArray(false) + .build(), + + "createdAt" to + ModelField.builder() + .name("createdAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build(), + + "updatedAt" to + ModelField.builder() + .name("updatedAt") + .javaClassForValue(Temporal.DateTime::class.java) + .targetType("AWSDateTime") + .isRequired(false) + .isArray(false) + .isReadOnly(true) + .build() + ) + ) + .associations( + mapOf( + "blog" to + ModelAssociation.builder() + .name("BelongsTo") + .targetNames(listOf("blogID", "blogName").toTypedArray()) + .build(), + "comments" to + ModelAssociation.builder() + .name("HasMany") + .associatedName("post") + .associatedType("Post") + .build() + + ) + ) + .modelClass(SerializedModel::class.java) + .version(1) .build() diff --git a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilderTest.kt b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilderTest.kt index f1d01bb392..98f64f4504 100644 --- a/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilderTest.kt +++ b/packages/amplify_datastore/android/src/test/kotlin/com/amazonaws/amplify/amplify_datastore/types/query/QueryPredicateBuilderTest.kt @@ -15,8 +15,11 @@ package com.amazonaws.amplify.amplify_datastore.types.query +import com.amazonaws.amplify.amplify_core.cast +import com.amazonaws.amplify.amplify_datastore.cpkPostSchema import com.amazonaws.amplify.amplify_datastore.postSchema import com.amazonaws.amplify.amplify_datastore.readMapFromFile +import com.amplifyframework.core.model.ModelIdentifier import com.amplifyframework.core.model.query.predicate.QueryField import com.amplifyframework.core.model.query.predicate.QueryPredicateGroup import com.amplifyframework.core.model.query.predicate.QueryPredicateOperation.not @@ -30,6 +33,11 @@ class QueryPredicateBuilderTest { private val rating: QueryField = QueryField.field("rating") private val created: QueryField = QueryField.field("created") private val blogID: QueryField = QueryField.field("blogID") + private val inventoryProductID = QueryField.field("productID") + private val inventoryName = QueryField.field("name") + private val inventoryWarehouseID = QueryField.field("warehouseID") + private val inventoryRegion = QueryField.field("region") + private val cpkBlogForeignKeyField = QueryField.field("@@blogForeignKey") @Test fun test_when_id_not_equals() { @@ -39,7 +47,7 @@ class QueryPredicateBuilderTest { readMapFromFile( "query_predicate", "id_not_equals.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -53,7 +61,7 @@ class QueryPredicateBuilderTest { "query_predicate", "rating_greater_or_equal.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -67,7 +75,7 @@ class QueryPredicateBuilderTest { "query_predicate", "complex_nested.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -84,7 +92,7 @@ class QueryPredicateBuilderTest { "query_predicate", "group_with_only_and.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -98,7 +106,7 @@ class QueryPredicateBuilderTest { "query_predicate", "group_mixed_and_or.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -112,7 +120,7 @@ class QueryPredicateBuilderTest { "query_predicate", "mixed_with_not.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -128,7 +136,7 @@ class QueryPredicateBuilderTest { "query_predicate", "negate_complex_predicate.json", HashMap::class.java - ) as HashMap + ).cast() ) ) } @@ -142,7 +150,7 @@ class QueryPredicateBuilderTest { "query_predicate", "relation_field_lookup.json", HashMap::class.java - ) as HashMap, + ).cast(), postSchema ) ) @@ -157,7 +165,91 @@ class QueryPredicateBuilderTest { "query_predicate", "query_predicate_constant_all.json", HashMap::class.java - ) as HashMap + ).cast() + ) + ) + } + + @Test + fun test_when_equals_model_identifier_used() { + Assert.assertEquals( + inventoryProductID.eq("product-id") + .and(inventoryName.eq("product-name")) + .and(inventoryWarehouseID.eq("warehouse-id")) + .and(inventoryRegion.eq("some region")), + QueryPredicateBuilder.fromSerializedMap( + readMapFromFile( + "query_predicate", "model_identifier_equals.json", + HashMap::class.java + ).cast() + ) + ) + } + + @Test + fun test_when_not_equals_model_identifier_used() { + Assert.assertEquals( + inventoryProductID.ne("product-id") + .and(inventoryName.ne("product-name")) + .and(inventoryWarehouseID.ne("warehouse-id")) + .and(inventoryRegion.ne("some region")), + QueryPredicateBuilder.fromSerializedMap( + readMapFromFile( + "query_predicate", "model_identifier_not_equals.json", + HashMap::class.java + ).cast() + ) + ) + } + + @Test + fun test_when_group_not_equals_model_identifier_used() { + Assert.assertEquals( + QueryPredicateGroup.not( + inventoryProductID.eq("product-id") + .and(inventoryName.eq("product-name")) + .and(inventoryWarehouseID.eq("warehouse-id")) + .and(inventoryRegion.eq("some region")) + ), + QueryPredicateBuilder.fromSerializedMap( + readMapFromFile( + "query_predicate", "model_identifier_group_not_equals.json", + HashMap::class.java + ).cast() + ) + ) + } + + @Test + fun test_when_group_equals_model_identifier_used() { + Assert.assertEquals( + QueryPredicateGroup.not( + inventoryProductID.ne("product-id") + .and(inventoryName.ne("product-name")) + .and(inventoryWarehouseID.ne("warehouse-id")) + .and(inventoryRegion.ne("some region")), + ), + QueryPredicateBuilder.fromSerializedMap( + readMapFromFile( + "query_predicate", "model_identifier_group_equals.json", + HashMap::class.java + ).cast() + ) + ) + } + + @Test + fun test_when_query_by_nested_model_identifier() { + Assert.assertEquals( + cpkBlogForeignKeyField.eq(ModelIdentifier.Helper.getIdentifier( + "123", listOf("the parent") + )), + QueryPredicateBuilder.fromSerializedMap( + readMapFromFile( + "query_predicate", "query_by_nested_model_identifier.json", + HashMap::class.java + ).cast(), + cpkPostSchema ) ) } diff --git a/packages/amplify_datastore/example/ios/Runner.xcodeproj/project.pbxproj b/packages/amplify_datastore/example/ios/Runner.xcodeproj/project.pbxproj index 01cea16d8a..0a59d7f723 100644 --- a/packages/amplify_datastore/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/amplify_datastore/example/ios/Runner.xcodeproj/project.pbxproj @@ -43,6 +43,11 @@ B4FD354C255D0A9D00A4E699 /* 1_result.json in Resources */ = {isa = PBXBuildFile; fileRef = B4FD354B255D0A9D00A4E699 /* 1_result.json */; }; D30253A827A1A89E0067A915 /* query_predicate_constant_all.json in Resources */ = {isa = PBXBuildFile; fileRef = D30253A727A1A89E0067A915 /* query_predicate_constant_all.json */; }; D3255F0326E81E3300063A15 /* custom_type_schema_maps.json in Resources */ = {isa = PBXBuildFile; fileRef = D3255F0226E81E3300063A15 /* custom_type_schema_maps.json */; }; + D3B1E07D283EB5DD0004F964 /* model_identifier_group_equals.json in Resources */ = {isa = PBXBuildFile; fileRef = D3B1E07C283EB5DD0004F964 /* model_identifier_group_equals.json */; }; + D3B1E07F283EB5F20004F964 /* model_identifier_group_not_equals.json in Resources */ = {isa = PBXBuildFile; fileRef = D3B1E07E283EB5F20004F964 /* model_identifier_group_not_equals.json */; }; + D3B1E081283EB6040004F964 /* model_identifier_not_equals.json in Resources */ = {isa = PBXBuildFile; fileRef = D3B1E080283EB6040004F964 /* model_identifier_not_equals.json */; }; + D3B1E082283EB8080004F964 /* model_identifier_equals.json in Resources */ = {isa = PBXBuildFile; fileRef = D3B1E07B283EB5BC0004F964 /* model_identifier_equals.json */; }; + D3B1E08428625F0D0004F964 /* relation_model_identifier_equals.json in Resources */ = {isa = PBXBuildFile; fileRef = D3B1E08328625F0D0004F964 /* relation_model_identifier_equals.json */; }; FB228242255D4C95004BFCC0 /* instance_without_predicate.json in Resources */ = {isa = PBXBuildFile; fileRef = FB228241255D4C95004BFCC0 /* instance_without_predicate.json */; }; /* End PBXBuildFile section */ @@ -112,6 +117,11 @@ B8F88CC4CFC43169A3129743 /* Pods-unit_tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-unit_tests.release.xcconfig"; path = "Target Support Files/Pods-unit_tests/Pods-unit_tests.release.xcconfig"; sourceTree = ""; }; D30253A727A1A89E0067A915 /* query_predicate_constant_all.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = query_predicate_constant_all.json; sourceTree = ""; }; D3255F0226E81E3300063A15 /* custom_type_schema_maps.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = custom_type_schema_maps.json; sourceTree = ""; }; + D3B1E07B283EB5BC0004F964 /* model_identifier_equals.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; lineEnding = 0; path = model_identifier_equals.json; sourceTree = ""; }; + D3B1E07C283EB5DD0004F964 /* model_identifier_group_equals.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = model_identifier_group_equals.json; sourceTree = ""; }; + D3B1E07E283EB5F20004F964 /* model_identifier_group_not_equals.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = model_identifier_group_not_equals.json; sourceTree = ""; }; + D3B1E080283EB6040004F964 /* model_identifier_not_equals.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = model_identifier_not_equals.json; sourceTree = ""; }; + D3B1E08328625F0D0004F964 /* relation_model_identifier_equals.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = relation_model_identifier_equals.json; sourceTree = ""; }; D5D88DACD96D3CAC9BEBB076 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; ED11E4916E10B172A89EC7E9 /* Pods-unit_tests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-unit_tests.profile.xcconfig"; path = "Target Support Files/Pods-unit_tests/Pods-unit_tests.profile.xcconfig"; sourceTree = ""; }; FB228241255D4C95004BFCC0 /* instance_without_predicate.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = instance_without_predicate.json; sourceTree = ""; }; @@ -230,6 +240,11 @@ B4A5C4582548F00900B9E501 /* negate_complex_predicate.json */, B4A5C4562548F00900B9E501 /* rating_greater_or_equal.json */, D30253A727A1A89E0067A915 /* query_predicate_constant_all.json */, + D3B1E07B283EB5BC0004F964 /* model_identifier_equals.json */, + D3B1E07C283EB5DD0004F964 /* model_identifier_group_equals.json */, + D3B1E07E283EB5F20004F964 /* model_identifier_group_not_equals.json */, + D3B1E080283EB6040004F964 /* model_identifier_not_equals.json */, + D3B1E08328625F0D0004F964 /* relation_model_identifier_equals.json */, ); path = predicates; sourceTree = ""; @@ -400,8 +415,10 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + D3B1E081283EB6040004F964 /* model_identifier_not_equals.json in Resources */, B4A5C4672549009900B9E501 /* bool_and_double_operands.json in Resources */, D3255F0326E81E3300063A15 /* custom_type_schema_maps.json in Resources */, + D3B1E082283EB8080004F964 /* model_identifier_equals.json in Resources */, B4A5C4512548EF9A00B9E501 /* id_not_equals.json in Resources */, 84A0308225771E15007106B9 /* serialized_model_maps.json in Resources */, 847189D82565FAF200D6798A /* model_schema_maps.json in Resources */, @@ -413,11 +430,14 @@ B4A5C45D2548F00900B9E501 /* group_mixed_and_or.json in Resources */, B4A5C45B2548F00900B9E501 /* mixed_with_not.json in Resources */, 9C44723B2559F95300557CB1 /* instance_no_predicate.json in Resources */, + D3B1E08428625F0D0004F964 /* relation_model_identifier_equals.json in Resources */, B409DE21254A218A006AECDB /* model_name_with_all_query_parameters.json in Resources */, B409DE1F254A218A006AECDB /* 2_results.json in Resources */, + D3B1E07D283EB5DD0004F964 /* model_identifier_group_equals.json in Resources */, B4A5C45E2548F00900B9E501 /* negate_complex_predicate.json in Resources */, D30253A827A1A89E0067A915 /* query_predicate_constant_all.json in Resources */, B4A5C45A2548F00900B9E501 /* group_with_only_and.json in Resources */, + D3B1E07F283EB5F20004F964 /* model_identifier_group_not_equals.json in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift index be3ddbc478..50d735e413 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/AmplifyModelSchemaUnitTests.swift @@ -32,7 +32,8 @@ class AmplifyModelSchemaUnitTests: XCTestCase { customTypeSchemasRegistry.addModelSchema( modelName: serializedCustomType["name"] as! String, modelSchema: try FlutterModelSchema( - serializedData: serializedCustomType + serializedData: serializedCustomType, + isModelType: false ).convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) ) } catch { @@ -99,7 +100,9 @@ class AmplifyModelSchemaUnitTests: XCTestCase { func test_model_nested_custom_type_schema() throws { let personModelSchema = try FlutterModelSchema( - serializedData: modelSchemaMap["PersonModelSchema"] as! [String: Any]) + serializedData: modelSchemaMap["PersonModelSchema"] as! [String: Any], + isModelType: false + ) .convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) let expectedPersonModelSchema = SchemaData.PersonSchema @@ -136,4 +139,12 @@ class AmplifyModelSchemaUnitTests: XCTestCase { contactSchemaFields!["mailingAddresses"]?.embeddedTypeSchema?.sortedFields ) } + + func test_custom_primary_key_model_schema() throws { + let inventoryModelSchema = try FlutterModelSchema( + serializedData: modelSchemaMap["InventoryModelSchema"] as! [String: Any] + ).convertToNativeModelSchema(customTypeSchemasRegistry: customTypeSchemasRegistry) + + XCTAssertEqual(SchemaData.InventorySchema, inventoryModelSchema) + } } diff --git a/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift index d6bb4e7ffc..ee3cef19c6 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/AmplifySerializedModelUnitTests.swift @@ -31,7 +31,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { ) let refMap = serializedModelMaps["BlogSerializedMap"] as! [String: Any] - XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] @@ -49,7 +48,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { ) let refMap = serializedModelMaps["CommentSerializedMap"] as! [String: Any] - XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] @@ -57,11 +55,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { XCTAssertEqual(ourSd["id"] as! String, refSd["id"] as! String) XCTAssertEqual(ourSd["content"] as! String, refSd["content"] as! String) - - let ourNs: [String: Any] = ourSd["post"] as! [String: Any] - let refNs: [String: Any] = refSd["post"] as! [String: Any] - - XCTAssertEqual(ourNs["id"] as! String, refNs["id"] as! String) } func test_post_with_datetime_int_hasMany_serialization() throws { @@ -72,7 +65,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { ) let refMap = serializedModelMaps["PostSerializedMap"] as! [String: Any] - XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] @@ -81,11 +73,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { XCTAssertEqual(ourSd["id"] as! String, refSd["id"] as! String) XCTAssertEqual(ourSd["title"] as! String, refSd["title"] as! String) XCTAssertEqual(ourSd["created"] as! String, refSd["created"] as! String) - - let ourNs: [String: Any] = ourSd["blog"] as! [String: Any] - let refNs: [String: Any] = refSd["blog"] as! [String: Any] - - XCTAssertEqual(ourNs["id"] as! String, refNs["id"] as! String) } func test_post_with_nested_models_serialization() throws { @@ -120,7 +107,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { ) let refMap = serializedModelMaps["AllTypeModelSerializedMap"] as! [String: Any] - XCTAssertEqual(ourMap["id"] as! String, refMap["id"] as! String) XCTAssertEqual(ourMap["modelName"] as! String, refMap["modelName"] as! String) let ourSd: [String: Any] = ourMap["serializedData"] as! [String: Any] @@ -143,7 +129,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { let testModelContent = "a comment" let jsonString = "{\"id\":\"\(testModelId)\",\"content\":\"\(testModelContent)\"}" let decodedModel = try ModelRegistry.decode(modelName: modelName, from: jsonString) - XCTAssertEqual(decodedModel.id, testModelId) let values = (decodedModel as! FlutterSerializedModel).values XCTAssertEqual(values["content"], JSONValue.string(testModelContent)) } @@ -154,7 +139,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { let testModelContent = "a comment" let jsonString = "[{\"id\":\"\(testModelId)\",\"content\":\"\(testModelContent)\"}]" let decodedModel = try ModelRegistry.decode(modelName: modelName, from: jsonString) - XCTAssertEqual(decodedModel.id, testModelId) let values = (decodedModel as! FlutterSerializedModel).values XCTAssertEqual(values["content"], JSONValue.string(testModelContent)) } @@ -178,7 +162,6 @@ class AmplifySerializedModelUnitTests: XCTestCase { ) let expected = serializedModelMaps["PersonModelSerializedMap"] as! [String: Any] - XCTAssertEqual(expected["id"] as! String, actual["id"] as! String) XCTAssertEqual(expected["modelName"] as! String, actual["modelName"] as! String) let actualSerializedData = actual["serializedData"] as! [String: Any] diff --git a/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift b/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift index 1fec05d9c0..37d95efc4d 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/DataStoreHubEventStreamHandlerTests.swift @@ -20,7 +20,7 @@ import Combine @testable import AWSPluginsCore @testable import amplify_datastore -let testHubSchema: ModelSchema = ModelSchema.init(name: "Post") +let testHubSchema: ModelSchema = SchemaData.PostSchema class DataStoreHubEventStreamHandlerTests: XCTestCase { var pluginUnderTest: SwiftAmplifyDataStorePlugin = .init() @@ -28,7 +28,7 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { var customTypeSchemaRegistry = FlutterSchemaRegistry() override func setUpWithError() throws { - modelSchemaRegistry.addModelSchema(modelName: "Post", modelSchema: testSchema) + modelSchemaRegistry.addModelSchema(modelName: "Post", modelSchema: testHubSchema) modelSchemaRegistry.registerModels(registry: ModelRegistry.self) } @@ -266,7 +266,7 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { "title": "Title 1" ] - let serializedModel = FlutterSerializedModel(id: uuid, map: try FlutterDataStoreRequestUtils.getJSONValue(modelMap)) + let serializedModel = FlutterSerializedModel(map: try FlutterDataStoreRequestUtils.getJSONValue(modelMap), modelName: "Post") let outboxMutationEnqueuedEvent = OutboxMutationEvent.fromModelWithoutMetadata(modelName: "Post", model: serializedModel) let hubHandler = MockDataStoreHubHandler() hubHandler.setExpectation(outerExpect: expect) @@ -311,7 +311,7 @@ class DataStoreHubEventStreamHandlerTests: XCTestCase { "title": "Title 1" ] - let serializedModel = FlutterSerializedModel(id: uuid, map: try FlutterDataStoreRequestUtils.getJSONValue(modelMap)) + let serializedModel = FlutterSerializedModel(map: try FlutterDataStoreRequestUtils.getJSONValue(modelMap), modelName: "Post") let syncMetadata = MutationSyncMetadata(id: uuid, deleted: false, diff --git a/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift index d815ab1de0..d129289dce 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/DataStorePluginUnitTests.swift @@ -20,12 +20,13 @@ import amplify_core @testable import AmplifyPlugins @testable import amplify_datastore -let testSchema: ModelSchema = ModelSchema.init(name: "Post") +let testSchema: ModelSchema = SchemaData.PostSchema let amplifySuccessResults: [FlutterSerializedModel] = (try! readJsonArray(filePath: "2_results") as! [[String: Any]]).map { serializedModel in FlutterSerializedModel.init( - id: serializedModel["id"] as! String, - map: try! getJSONValue(serializedModel["serializedData"] as! [String: Any])) + map: try! getJSONValue(serializedModel["serializedData"] as! [String: Any]), + modelName: serializedModel["modelName"] as! String + ) } let id: QueryField = field("id") @@ -82,14 +83,12 @@ class DataStorePluginUnitTests: XCTestCase { flutterResult: { results in if let results = results as? [[String: Any]] { // Result #1 (Any/AnyObject is not equatable so we iterate over fields we know) - XCTAssertEqual("4281dfba-96c8-4a38-9a8e-35c7e893ea47", results[0]["id"] as! String) XCTAssertEqual("Post", results[0]["modelName"] as! String) XCTAssertEqual("4281dfba-96c8-4a38-9a8e-35c7e893ea47", (results[0]["serializedData"] as! [String: Any])["id"] as! String) XCTAssertEqual("Title 1", (results[0]["serializedData"] as! [String: Any])["title"] as! String) - XCTAssertEqual(4, (results[0]["serializedData"] as! [String: Any])["rating"] as? Double) // Fixme, manually testing results in int + XCTAssertEqual(4, (results[0]["serializedData"] as! [String: Any])["rating"] as? Int) // Fixme, manually testing results in int // Result #2 - XCTAssertEqual("43036c6b-8044-4309-bddc-262b6c686026", results[1]["id"] as! String) XCTAssertEqual("Post", results[1]["modelName"] as! String) XCTAssertEqual("43036c6b-8044-4309-bddc-262b6c686026", (results[1]["serializedData"] as! [String: Any])["id"] as! String) XCTAssertEqual("Title 2", (results[1]["serializedData"] as! [String: Any])["title"] as! String) @@ -215,11 +214,10 @@ class DataStorePluginUnitTests: XCTestCase { XCTAssertEqual("create", flutterEvent["eventType"] as! String) let item = flutterEvent["item"] as! [String: Any] - XCTAssertEqual("4281dfba-96c8-4a38-9a8e-35c7e893ea47", item["id"] as! String) XCTAssertEqual("Post", item["modelName"] as! String) XCTAssertEqual("4281dfba-96c8-4a38-9a8e-35c7e893ea47", (item["serializedData"] as! [String: Any])["id"] as! String) XCTAssertEqual("Title 1", (item["serializedData"] as! [String: Any])["title"] as! String) - XCTAssertEqual(4, (item["serializedData"] as! [String: Any])["rating"] as? Double) // Fixme, manually testing results in int + XCTAssertEqual(4, (item["serializedData"] as! [String: Any])["rating"] as? Int) // Fixme, manually testing results in int } } @@ -478,7 +476,6 @@ class DataStorePluginUnitTests: XCTestCase { completion: @escaping DataStoreCallback) throws { // Validations that we called the native library correctly - XCTAssertEqual("9fc5fab4-37ff-4566-97e5-19c5d58a4c22", serializedModel.id) XCTAssertEqual(testSchema.name, modelSchema.name) XCTAssertNil(predicate) // Return from the mock @@ -507,7 +504,6 @@ class DataStorePluginUnitTests: XCTestCase { completion: @escaping DataStoreCallback) throws { // Validations that we called the native library correctly - XCTAssertEqual("9fc5fab4-37ff-4566-97e5-19c5d58a4c22", serializedModel.id) XCTAssertEqual(testSchema.name, modelSchema.name) XCTAssertNil(predicate) // Return from the mock diff --git a/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift b/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift index 86efa864a9..98cfe5bcaf 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/QueryPredicateBuilderUnitTests.swift @@ -22,6 +22,11 @@ class QueryPredicateBuilderUnitTests: XCTestCase { private let title: QueryField = field("title") private let rating: QueryField = field("rating") private let created: QueryField = field("created") + private let inventoryProductID: QueryField = field("productID") + private let inventoryName: QueryField = field("name") + private let inventoryWarehouseID: QueryField = field("warehouseID") + private let inventoryRegion: QueryField = field("region") + private let hasManyParent: QueryField = field("hasManyParent") func test_when_id_not_equals() throws { XCTAssertEqual( @@ -99,4 +104,62 @@ class QueryPredicateBuilderUnitTests: XCTestCase { ) as! QueryPredicateConstant ) } + + func test_when_equals_model_identifier_used() throws { + XCTAssertEqual( + inventoryProductID.eq("product-id") + .and(inventoryName.eq("product-name")) + .and(inventoryWarehouseID.eq("warehouse-id")) + .and(inventoryRegion.eq("some region")), + try QueryPredicateBuilder.fromSerializedMap(readJsonMap(filePath: "model_identifier_equals")) as! QueryPredicateGroup + ) + } + + func test_when_not_equals_model_identifier_used() throws { + XCTAssertEqual( + inventoryProductID.ne("product-id") + .and(inventoryName.ne("product-name")) + .and(inventoryWarehouseID.ne("warehouse-id")) + .and(inventoryRegion.ne("some region")), + try QueryPredicateBuilder.fromSerializedMap(readJsonMap(filePath: "model_identifier_not_equals")) as! QueryPredicateGroup + ) + } + + func test_when_group_not_equals_model_identifier_used() throws { + XCTAssertEqual( + not( + inventoryProductID.eq("product-id") + .and(inventoryName.eq("product-name")) + .and(inventoryWarehouseID.eq("warehouse-id")) + .and(inventoryRegion.eq("some region")) + ), + try QueryPredicateBuilder.fromSerializedMap(readJsonMap(filePath: "model_identifier_group_not_equals")) as! QueryPredicateGroup + ) + } + + func test_when_group_equals_model_identifier_used() throws { + XCTAssertEqual( + not( + inventoryProductID.ne("product-id") + .and(inventoryName.ne("product-name")) + .and(inventoryWarehouseID.ne("warehouse-id")) + .and(inventoryRegion.ne("some region")) + ), + try QueryPredicateBuilder.fromSerializedMap(readJsonMap(filePath: "model_identifier_group_equals")) as! QueryPredicateGroup + ) + } + + func test_when_query_associated_model_identifier_used() throws { + XCTAssertEqual( + hasManyParent.eq( + FlutterSerializedModel.Identifier.make( + fields: [ + (name: "id", value: "parent-id"), + (name: "name", value: "parent-name") + ] + ).stringValue + ), + try QueryPredicateBuilder.fromSerializedMap(readJsonMap(filePath: "relation_model_identifier_equals")) as! QueryPredicateOperation + ) + } } diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift b/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift index 0c411efe5e..da8fa7ade5 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/FlutterSerializedModelData.swift @@ -19,21 +19,21 @@ import Amplify struct FlutterSerializedModelData { static var BlogSerializedModel: FlutterSerializedModel = - .init(id: "999", map: [ + .init(map: [ "id": JSONValue.string("999"), "name": JSONValue.string("blog name"), - ]) + ], modelName: "Blog") static var CommentSerializedModel: FlutterSerializedModel = - .init(id: "999", map: [ + .init(map: [ "id": JSONValue.string("999"), "post": JSONValue.object([ "id": "555" ]), "content": "content" - ]) + ], modelName: "Comment") static var PostSerializedModel: FlutterSerializedModel = - .init(id: "999", map: [ + .init(map: [ "id": JSONValue.string("999"), "title": JSONValue.string("post title"), "created": JSONValue.string("2020-11-25T01:28:49.000Z"), @@ -50,10 +50,10 @@ struct FlutterSerializedModelData { "description": "Testing department 1" ]) ]) - ]) + ], modelName: "Post") static var AllTypeModelSerializedModel: FlutterSerializedModel = - .init(id: "999", map: [ + .init(map: [ "id": JSONValue.string("999"), "stringType": JSONValue.string("string value"), "intType": JSONValue.number(10), @@ -64,11 +64,10 @@ struct FlutterSerializedModelData { "timeType": JSONValue.string("20:20:20:020Z"), "timestampType": JSONValue.number(999), "enumType": JSONValue.string("maybe") - ]) + ], modelName: "AllTypeModel") static var PersonModelSerializedModel: FlutterSerializedModel = .init( - id: "123", map: [ "id": JSONValue.string("123"), "name": JSONValue.string("Tester Testing"), @@ -111,6 +110,7 @@ struct FlutterSerializedModelData { "field": "just a string" ]) ]) - ] + ], + modelName: "Person" ) } diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift b/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift index 059e7a214d..f06435021f 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/SchemaData.swift @@ -21,6 +21,7 @@ struct SchemaData { static var PostSchema: ModelSchema = .init( name: "Post", pluralName: "Posts", + attributes: [.index(fields: ["blogID"], name: "byBlog")], fields: [ "id": ModelField(name: "id", type: .string, isRequired: true, isArray: false), "title": ModelField(name: "title", type: .string, isRequired: true, isArray: false), @@ -31,7 +32,8 @@ struct SchemaData { "author": ModelField(name: "author", type: .model(name: "Author"), isRequired: true, isArray: false, association: ModelAssociation.belongsTo(targetName: "authorId")), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var CommentSchema: ModelSchema = .init( @@ -43,7 +45,8 @@ struct SchemaData { "content": ModelField(name: "content", type: .string, isRequired: true, isArray: false), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var BlogSchema: ModelSchema = .init( @@ -55,7 +58,8 @@ struct SchemaData { "posts": ModelField(name: "posts", type: .collection(of: "Post"), isRequired: false, isArray: true, association: ModelAssociation.hasMany(associatedFieldName: "blog")), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var PostAuthComplexSchema: ModelSchema = .init( @@ -77,7 +81,8 @@ struct SchemaData { "owner": ModelField(name: "owner", type: .string, isRequired: false, isArray: false), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var PostAuthComplexWithProviderUserPoolsSchema: ModelSchema = .init( @@ -99,7 +104,8 @@ struct SchemaData { "owner": ModelField(name: "owner", type: .string, isRequired: false, isArray: false), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var PostAuthComplexWithProviderApiKeySchema: ModelSchema = .init( @@ -118,7 +124,8 @@ struct SchemaData { "id": ModelField(name: "id", type: .string, isRequired: true, isArray: false), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var AllTypeModelSchema: ModelSchema = .init( @@ -137,7 +144,8 @@ struct SchemaData { "enumType": ModelField(name: "enumType", type: .string, isRequired: true, isArray: false), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var AuthorModelSchema: ModelSchema = .init( @@ -149,7 +157,8 @@ struct SchemaData { "department": ModelField(name: "department", type: .model(name: "Department"), isRequired: true, isArray: false, association: ModelAssociation.belongsTo(targetName: "departmentId")), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var DepartmentSchema: ModelSchema = .init( @@ -161,7 +170,8 @@ struct SchemaData { "description": ModelField(name: "description", type: .string, isRequired: true, isArray: false), "createdAt": ModelField(name: "createdAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), "updatedAt": ModelField(name: "updatedAt", type: .dateTime, isRequired: false, isReadOnly: true, isArray: false), - ] + ], + primaryKeyFieldKeys: ["id"] ) static var AddressSchema: ModelSchema = .init( @@ -230,7 +240,23 @@ struct SchemaData { isArray: true ), "anotherCustomTypeTree": ModelField(name: "anotherCustomTypeTree", type: .embedded(type: JSONValue.self, schema: SchemaData.CustomASchema)), - ] + ], + primaryKeyFieldKeys: ["id"] + ) + + static var InventorySchema: ModelSchema = .init( + name: "Inventory", + pluralName: "Inventories", + attributes: [ + .index(fields: ["productID", "name", "warehouseID", "region"], name: nil) + ], + fields: [ + "productID": ModelField(name: "productID", type: .string, isRequired: true, isArray: false), + "name": ModelField(name: "name", type: .string, isRequired: true, isArray: false), + "warehouseID": ModelField(name: "warehouseID", type: .string, isRequired: true, isArray: false), + "region": ModelField(name: "region", type: .string, isRequired: true, isArray: false), + ], + primaryKeyFieldKeys: ["productID", "name", "warehouseID", "region"] ) static var modelSchemas: [String: ModelSchema] { @@ -242,7 +268,8 @@ struct SchemaData { AllTypeModelSchema.name: AllTypeModelSchema, AuthorModelSchema.name: AuthorModelSchema, DepartmentSchema.name: DepartmentSchema, - PersonSchema.name: PersonSchema + PersonSchema.name: PersonSchema, + InventorySchema.name: InventorySchema, ] } diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/model_schema_maps.json b/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/model_schema_maps.json index f86c2fb6fb..2a49f2253d 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/model_schema_maps.json +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/model_schema_maps.json @@ -117,6 +117,12 @@ "PostSchema": { "name": "Post", "pluralName": "Posts", + "indexes": [ + { + "name": "byBlog", + "fields": ["blogID"] + } + ], "fields": { "id": { "name": "id", @@ -552,5 +558,53 @@ "isReadOnly": true } } + }, + "InventoryModelSchema": { + "pluralName": "Inventories", + "name": "Inventory", + "indexes": [ + { + "name": null, + "fields": ["productID", "name", "warehouseID", "region"] + } + ], + "fields": { + "productID": { + "name": "productID", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + }, + "name": { + "name": "name", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + }, + "warehouseID": { + "name": "warehouseID", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + }, + "region": { + "name": "region", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + } + } } } diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/serialized_model_maps.json b/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/serialized_model_maps.json index 01bb4ae53a..4953f253ee 100644 --- a/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/serialized_model_maps.json +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/modelSchema/serialized_model_maps.json @@ -1,6 +1,5 @@ { "BlogSerializedMap": { - "id": "999", "modelName": "Blog", "serializedData": { "id": "999", @@ -8,7 +7,6 @@ } }, "CommentSerializedMap": { - "id": "999", "modelName": "Comment", "serializedData": { "id": "999", @@ -19,7 +17,6 @@ } }, "PostSerializedMap": { - "id": "999", "modelName": "Post", "serializedData": { "id": "999", @@ -53,7 +50,6 @@ } }, "AllTypeModelSerializedMap": { - "id": "999", "modelName": "AllTypeModel", "serializedData": { "id": "999", @@ -69,7 +65,6 @@ } }, "PersonModelSerializedMap": { - "id": "123", "modelName": "Person", "serializedData": { "id": "123", diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_equals.json b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_equals.json new file mode 100644 index 0000000000..f14ab765ac --- /dev/null +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_equals.json @@ -0,0 +1,19 @@ +{ + "queryByIdentifierOperation": { + "operatorName": "equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } +} diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_equals.json b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_equals.json new file mode 100644 index 0000000000..6c7baece0e --- /dev/null +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_equals.json @@ -0,0 +1,26 @@ +{ + "queryPredicateGroup": { + "type": "not", + "predicates": [ + { + "queryByIdentifierOperation": { + "operatorName": "not_equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } + } + ] + } +} diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_not_equals.json b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_not_equals.json new file mode 100644 index 0000000000..121219070c --- /dev/null +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_group_not_equals.json @@ -0,0 +1,26 @@ +{ + "queryPredicateGroup": { + "type": "not", + "predicates": [ + { + "queryByIdentifierOperation": { + "operatorName": "equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } + } + ] + } +} diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_not_equals.json b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_not_equals.json new file mode 100644 index 0000000000..0ef0745316 --- /dev/null +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/model_identifier_not_equals.json @@ -0,0 +1,19 @@ +{ + "queryByIdentifierOperation": { + "operatorName": "not_equal", + "value": [ + { + "productID": "product-id" + }, + { + "name": "product-name" + }, + { + "warehouseID": "warehouse-id" + }, + { + "region": "some region" + } + ] + } +} diff --git a/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/relation_model_identifier_equals.json b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/relation_model_identifier_equals.json new file mode 100644 index 0000000000..e1461e9a40 --- /dev/null +++ b/packages/amplify_datastore/example/ios/unit_tests/resources/query/predicates/relation_model_identifier_equals.json @@ -0,0 +1,16 @@ +{ + "queryPredicateOperation": { + "field": "hasManyParent", + "fieldOperator": { + "operatorName": "equal", + "value": [ + { + "id": "parent-id" + }, + { + "name": "parent-name" + } + ] + } + } +} diff --git a/packages/amplify_datastore/test/resources/model_schema/model_schema_maps.json b/packages/amplify_datastore/test/resources/model_schema/model_schema_maps.json index 5f3d8e21e3..a5c21a699b 100644 --- a/packages/amplify_datastore/test/resources/model_schema/model_schema_maps.json +++ b/packages/amplify_datastore/test/resources/model_schema/model_schema_maps.json @@ -115,6 +115,12 @@ "PostSchema": { "name": "Post", "pluralName": "Posts", + "indexes": [ + { + "name": "byBlog", + "fields": ["blogID"] + } + ], "fields": { "id": { "name": "id", @@ -532,5 +538,58 @@ "isReadOnly": true } } + }, + "InventoryModelSchema": { + "pluralName": "Inventories", + "name": "Inventory", + "indexes": [ + { + "name": null, + "fields": [ + "productID", + "name", + "warehouseID", + "region" + ] + } + ], + "fields": { + "productID": { + "name": "productID", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + }, + "name": { + "name": "name", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + }, + "warehouseID": { + "name": "warehouseID", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + }, + "region": { + "name": "region", + "type": { + "fieldType": "string" + }, + "isRequired": true, + "isArray": false, + "isReadOnly": false + } + } } } diff --git a/packages/amplify_datastore/test/resources/model_schema/serialized_model_maps.json b/packages/amplify_datastore/test/resources/model_schema/serialized_model_maps.json index d0d4954de8..1bc7838786 100644 --- a/packages/amplify_datastore/test/resources/model_schema/serialized_model_maps.json +++ b/packages/amplify_datastore/test/resources/model_schema/serialized_model_maps.json @@ -1,6 +1,5 @@ { "BlogSerializedMap" : { - "id" : "999", "modelName" : "Blog", "serializedData" : { "id" : "999", @@ -8,7 +7,6 @@ } }, "CommentSerializedMap" : { - "id" : "999", "modelName" : "Comment", "serializedData" : { "id" : "999", @@ -19,7 +17,6 @@ } }, "PostSerializedMap" : { - "id" : "999", "modelName" : "Post", "serializedData" : { "id" : "999", @@ -31,7 +28,6 @@ } }, "AllTypeModelSerializedMap" : { - "id" : "999", "modelName" : "AllTypeModel", "serializedData" : { "id" : "999", @@ -47,7 +43,6 @@ } }, "PersonModelSerializedMap": { - "id": "123", "modelName": "Person", "serializedData": { "id": "123", diff --git a/packages/amplify_datastore/test/resources/observe_api/blog_type_success_event.json b/packages/amplify_datastore/test/resources/observe_api/blog_type_success_event.json index ed8da01c25..be39bb8c3f 100644 --- a/packages/amplify_datastore/test/resources/observe_api/blog_type_success_event.json +++ b/packages/amplify_datastore/test/resources/observe_api/blog_type_success_event.json @@ -1,7 +1,6 @@ { "eventType": "create", "item": { - "id": "43036c6b-8044-4309-bddc-262b6c686026", "modelName": "Blog", "serializedData": { "id": "43036c6b-8044-4309-bddc-262b6c686026", diff --git a/packages/amplify_datastore/test/resources/observe_api/post_type_success_event.json b/packages/amplify_datastore/test/resources/observe_api/post_type_success_event.json index 0f666a1df9..dca16413e9 100644 --- a/packages/amplify_datastore/test/resources/observe_api/post_type_success_event.json +++ b/packages/amplify_datastore/test/resources/observe_api/post_type_success_event.json @@ -1,7 +1,6 @@ { "eventType": "create", "item": { - "id": "43036c6b-8044-4309-bddc-262b6c686026", "modelName": "Post", "serializedData": { "id": "43036c6b-8044-4309-bddc-262b6c686026", diff --git a/packages/amplify_datastore/test/resources/query_api/response/2_results.json b/packages/amplify_datastore/test/resources/query_api/response/2_results.json index ccb2021d45..56aa336958 100644 --- a/packages/amplify_datastore/test/resources/query_api/response/2_results.json +++ b/packages/amplify_datastore/test/resources/query_api/response/2_results.json @@ -1,6 +1,5 @@ [ { - "id": "4281dfba-96c8-4a38-9a8e-35c7e893ea47", "modelName": "Post", "serializedData": { "id": "4281dfba-96c8-4a38-9a8e-35c7e893ea47", @@ -10,7 +9,6 @@ } }, { - "id": "43036c6b-8044-4309-bddc-262b6c686026", "modelName": "Post", "serializedData": { "id": "43036c6b-8044-4309-bddc-262b6c686026", diff --git a/packages/amplify_datastore/test/resources/query_api/response/nested_results.json b/packages/amplify_datastore/test/resources/query_api/response/nested_results.json index 5c72501f6e..13ed7070d1 100644 --- a/packages/amplify_datastore/test/resources/query_api/response/nested_results.json +++ b/packages/amplify_datastore/test/resources/query_api/response/nested_results.json @@ -1,6 +1,5 @@ [ { - "id" : "39c3c0e6-8726-436e-8cdf-bff38e9a62da", "modelName" : "Comment", "serializedData" : { "id" : "39c3c0e6-8726-436e-8cdf-bff38e9a62da", diff --git a/packages/amplify_datastore/test/resources/query_predicate/query_by_nested_model_identifier.json b/packages/amplify_datastore/test/resources/query_predicate/query_by_nested_model_identifier.json new file mode 100644 index 0000000000..c60ec611d4 --- /dev/null +++ b/packages/amplify_datastore/test/resources/query_predicate/query_by_nested_model_identifier.json @@ -0,0 +1,12 @@ +{ + "queryPredicateOperation": { + "field": "blog", + "fieldOperator": { + "operatorName": "equal", + "value": [ + { "id": "123" }, + { "name": "the parent" } + ] + } + } +} diff --git a/packages/api/amplify_api_android/android/src/test/kotlin/com/amazonaws/amplify/amplify_api/AuthProviderTests.kt b/packages/api/amplify_api_android/android/src/test/kotlin/com/amazonaws/amplify/amplify_api/AuthProviderTests.kt index 97213e49e7..b8a738494b 100644 --- a/packages/api/amplify_api_android/android/src/test/kotlin/com/amazonaws/amplify/amplify_api/AuthProviderTests.kt +++ b/packages/api/amplify_api_android/android/src/test/kotlin/com/amazonaws/amplify/amplify_api/AuthProviderTests.kt @@ -48,7 +48,6 @@ import org.mockito.kotlin.verify * Mock model object for building dummy GraphQL requests. */ class MockModel : Model { - override fun getId(): String = "12345" } /** From d778a5399eeb97d1fb86b5a570e3e2880d287644 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 26 May 2022 11:41:16 -0700 Subject: [PATCH 06/10] feat(datastore): add targetNames support for codegen --- .../src/types/models/model_association.dart | 52 ++++++++----------- .../types/models/model_field_definition.dart | 5 +- .../types/model/FlutterModelAssociation.kt | 27 +++++----- .../types/model/FlutterModelAssociation.swift | 23 ++++++-- 4 files changed, 58 insertions(+), 49 deletions(-) diff --git a/packages/amplify_core/lib/src/types/models/model_association.dart b/packages/amplify_core/lib/src/types/models/model_association.dart index 5e43413ace..605c371502 100644 --- a/packages/amplify_core/lib/src/types/models/model_association.dart +++ b/packages/amplify_core/lib/src/types/models/model_association.dart @@ -14,34 +14,49 @@ */ import 'dart:convert'; +import 'package:aws_common/aws_common.dart'; import 'package:flutter/foundation.dart'; // ignore: constant_identifier_names enum ModelAssociationEnum { HasMany, HasOne, BelongsTo } @immutable -class ModelAssociation { +class ModelAssociation with AWSEquatable, AWSSerializable { final ModelAssociationEnum associationType; - final String? targetName; // opt (used in belongsTo) - final String? associatedName; // opt (used in hasMany/hasOne) - final String? associatedType; // opt (used in hasMany/hasOne) + final String? targetName; // used in belongsTo + final List? targetNames; // used in belongsTo + final String? associatedName; // used in hasMany/hasOne + final String? associatedType; // used in hasMany/hasOne const ModelAssociation({ required this.associationType, - this.targetName, + @Deprecated('Please use the latest version of Amplify CLI to regenerate models') + this.targetName, + this.targetNames, this.associatedName, this.associatedType, }); + @override + List get props => [ + associationType, + targetName, + targetNames, + associatedName, + associatedType, + ]; + ModelAssociation copyWith({ ModelAssociationEnum? associationType, String? targetName, + List? targetNames, String? associatedName, String? associatedType, }) { return ModelAssociation( associationType: associationType ?? this.associationType, targetName: targetName ?? this.targetName, + targetNames: targetNames ?? this.targetNames, associatedName: associatedName ?? this.associatedName, associatedType: associatedType ?? this.associatedType, ); @@ -51,6 +66,7 @@ class ModelAssociation { final map = { 'associationType': describeEnum(associationType), 'targetName': targetName, + 'targetNames': targetNames, 'associatedName': associatedName, 'associatedType': associatedType, }; @@ -62,37 +78,15 @@ class ModelAssociation { return ModelAssociation( associationType: map['associationType'], targetName: map['targetName'], + targetNames: map['targetNames'], associatedName: map['associatedName'], associatedType: map['associatedType'], ); } + @override String toJson() => json.encode(toMap()); factory ModelAssociation.fromJson(String source) => ModelAssociation.fromMap(json.decode(source)); - - @override - String toString() { - return 'ModelAssociation(associationType: $associationType, targetName: $targetName, associatedName: $associatedName, associatedType: $associatedType)'; - } - - @override - bool operator ==(Object other) { - if (identical(this, other)) return true; - - return other is ModelAssociation && - other.associationType == associationType && - other.targetName == targetName && - other.associatedName == associatedName && - other.associatedType == associatedType; - } - - @override - int get hashCode { - return associationType.hashCode ^ - targetName.hashCode ^ - associatedName.hashCode ^ - associatedType.hashCode; - } } diff --git a/packages/amplify_core/lib/src/types/models/model_field_definition.dart b/packages/amplify_core/lib/src/types/models/model_field_definition.dart index 8142df19a1..b03bb5e619 100644 --- a/packages/amplify_core/lib/src/types/models/model_field_definition.dart +++ b/packages/amplify_core/lib/src/types/models/model_field_definition.dart @@ -150,7 +150,9 @@ class ModelFieldDefinition { bool isRequired = true, required String ofModelName, QueryField? associatedKey, - String? targetName}) { + @Deprecated('Please use the latest version of Amplify CLI to regenerate models') + String? targetName, + List? targetNames}) { // Extra code needed due to lack of nullability support String? associatedName; String? associatedType; @@ -166,6 +168,7 @@ class ModelFieldDefinition { association: ModelAssociation( associationType: ModelAssociationEnum.BelongsTo, targetName: targetName, + targetNames: targetNames, associatedName: associatedName, associatedType: associatedType)); } diff --git a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelAssociation.kt b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelAssociation.kt index 2e4d9fb91c..0e25f9e5bb 100644 --- a/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelAssociation.kt +++ b/packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelAssociation.kt @@ -15,29 +15,28 @@ package com.amazonaws.amplify.amplify_datastore.types.model +import com.amazonaws.amplify.amplify_core.cast import com.amplifyframework.core.model.ModelAssociation data class FlutterModelAssociation(val map: Map) { private val associationType: String = map["associationType"] as String - private val targetName: String? = map["targetName"] as String? + private val targetNames = when (val targetNames = map["targetNames"]) { + is List<*> -> targetNames.cast() + else -> when (val targetName = map["targetName"]) { + is String -> listOf(targetName) + else -> null + } + } private val associatedName: String? = map["associatedName"] as String? private val associatedType: String? = map["associatedType"] as String? fun convertToNativeModelAssociation(): ModelAssociation { - val builder: ModelAssociation.Builder = ModelAssociation.builder() + return ModelAssociation.builder() .name(associationType) - - if (!targetName.isNullOrEmpty()) { - builder.targetName(targetName) - } - if (!associatedName.isNullOrEmpty()) { - builder.associatedName(associatedName) - } - if (!associatedType.isNullOrEmpty()) { - builder.associatedType(associatedType) - } - - return builder.build() + .targetNames(targetNames?.toTypedArray()) + .associatedName(associatedName) + .associatedType(associatedType) + .build() } } diff --git a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift index 7fe0d5fdba..668a476850 100644 --- a/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift +++ b/packages/amplify_datastore/ios/Classes/types/model/FlutterModelAssociation.swift @@ -15,10 +15,11 @@ import Foundation import Amplify +import amplify_core public struct FlutterModelAssociation { private let associationType: String - private let targetName: String? + private var targetNames = [String]() private let associatedName: String? init(serializedData: [String: Any]) throws { @@ -31,18 +32,30 @@ public struct FlutterModelAssociation { } self.associationType = associationType - self.targetName = serializedData["targetName"] as? String + // With custom primary key we are expecting model to provide targetNames instead of targetName + // For belongsTo model association, if this information is missing, mostl likely + // Flutter sent wrongly serialized data + // Also, keeping targetName for backwards compatibility + if let inputTargetName = serializedData["targetName"] as? String { + targetNames.append(inputTargetName) + } else if let inputTargetNames = serializedData["targetNames"] as? [String] { + targetNames += inputTargetNames + } else if associationType == "BelongsTo" { + throw DataStoreError.decodingError( + "Invalid ModelAssociation data: targetNames is not presented in the serialized ModelAssociation data", + ErrorMessages.missingAttribute) + } self.associatedName = serializedData["associatedName"] as? String } public func convertToNativeModelAssociation() -> ModelAssociation{ switch associationType { case "HasMany": - return ModelAssociation.hasMany(associatedFieldName: associatedName) + return .hasMany(associatedFieldName: associatedName) case "HasOne": - return ModelAssociation.hasOne(associatedFieldName: associatedName) + return .hasOne(associatedFieldName: associatedName, targetNames: targetNames) case "BelongsTo": - return ModelAssociation.belongsTo(associatedFieldName: associatedName, targetName: targetName) + return .belongsTo(associatedFieldName: associatedName, targetNames: targetNames) default: preconditionFailure("Could not create a ModelAssociation from \(associationType)") } From 5b6e05463c725a8abcc2771ac33147690cbc7f8f Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 23 May 2022 13:33:21 -0700 Subject: [PATCH 07/10] chore(datastore): update integration tests model schema --- .../lib/models/BelongsToChildExplicit.dart | 62 ++- .../lib/models/BelongsToChildImplicit.dart | 62 ++- .../example/lib/models/BelongsToParent.dart | 59 ++- .../example/lib/models/Blog.dart | 63 ++- .../example/lib/models/Comment.dart | 71 ++- .../CpkHasManyChildBidirectionalExplicit.dart | 267 +++++++++++ .../CpkHasManyChildBidirectionalImplicit.dart | 267 +++++++++++ ...CpkHasManyParentBidirectionalExplicit.dart | 284 +++++++++++ ...CpkHasManyParentBidirectionalImplicit.dart | 284 +++++++++++ ...CpkHasManyUnidirectionalChildExplicit.dart | 303 ++++++++++++ ...CpkHasManyUnidirectionalChildImplicit.dart | 304 ++++++++++++ .../CpkHasManyUnidirectionalParent.dart | 312 ++++++++++++ .../models/CpkHasOneUnidirectionalChild.dart | 228 +++++++++ .../models/CpkHasOneUnidirectionalParent.dart | 399 ++++++++++++++++ .../example/lib/models/CpkInventory.dart | 311 ++++++++++++ .../example/lib/models/CpkManyToManyPost.dart | 238 ++++++++++ .../example/lib/models/CpkManyToManyTag.dart | 258 ++++++++++ ...kOneToOneBidirectionalChildExplicitCD.dart | 268 +++++++++++ ...kOneToOneBidirectionalChildExplicitID.dart | 268 +++++++++++ ...kOneToOneBidirectionalChildImplicitCD.dart | 271 +++++++++++ ...kOneToOneBidirectionalChildImplicitID.dart | 271 +++++++++++ .../CpkOneToOneBidirectionalParentCD.dart | 443 ++++++++++++++++++ .../CpkOneToOneBidirectionalParentID.dart | 426 +++++++++++++++++ .../example/lib/models/CpkPostTags.dart | 272 +++++++++++ .../CustomTypeWithAppsyncScalarTypes.dart | 4 +- .../example/lib/models/EnumField.dart | 2 +- .../HasManyChildBiDirectionalExplicit.dart | 71 ++- .../HasManyChildBiDirectionalImplicit.dart | 69 ++- .../lib/models/HasManyChildExplicit.dart | 71 ++- .../lib/models/HasManyChildImplicit.dart | 59 ++- .../example/lib/models/HasManyParent.dart | 58 ++- .../HasManyParentBiDirectionalExplicit.dart | 63 ++- .../HasManyParentBiDirectionalImplicit.dart | 63 ++- .../example/lib/models/HasOneChild.dart | 57 ++- .../example/lib/models/HasOneParent.dart | 58 ++- .../example/lib/models/ModelProvider.dart | 133 +++++- .../models/ModelWithAppsyncScalarTypes.dart | 62 ++- .../lib/models/ModelWithCustomType.dart | 60 ++- .../example/lib/models/ModelWithEnum.dart | 57 ++- .../lib/models/MultiRelatedAttendee.dart | 64 ++- .../lib/models/MultiRelatedMeeting.dart | 69 ++- .../lib/models/MultiRelatedRegistration.dart | 84 +++- .../example/lib/models/Post.dart | 76 ++- .../example/lib/models/PostTags.dart | 78 ++- .../example/lib/models/SimpleCustomType.dart | 10 +- .../example/lib/models/Tag.dart | 65 ++- .../example/tool/schema.graphql | 101 ++++ 47 files changed, 7166 insertions(+), 259 deletions(-) create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalExplicit.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalImplicit.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalExplicit.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalImplicit.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildExplicit.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildImplicit.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalParent.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalChild.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalParent.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkInventory.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkManyToManyPost.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkManyToManyTag.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitCD.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitID.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitCD.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitID.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentCD.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentID.dart create mode 100644 packages/amplify_datastore/example/lib/models/CpkPostTags.dart diff --git a/packages/amplify_datastore/example/lib/models/BelongsToChildExplicit.dart b/packages/amplify_datastore/example/lib/models/BelongsToChildExplicit.dart index 8a18880e85..755f4f98b9 100644 --- a/packages/amplify_datastore/example/lib/models/BelongsToChildExplicit.dart +++ b/packages/amplify_datastore/example/lib/models/BelongsToChildExplicit.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the BelongsToChildExplicit type in your schema. @@ -36,9 +36,13 @@ class BelongsToChildExplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + BelongsToChildExplicitModelIdentifier get modelIdentifier { + return BelongsToChildExplicitModelIdentifier(id: id); } String? get name { @@ -109,9 +113,9 @@ class BelongsToChildExplicit extends Model { } BelongsToChildExplicit copyWith( - {String? id, String? name, BelongsToParent? belongsToParent}) { + {String? name, BelongsToParent? belongsToParent}) { return BelongsToChildExplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, belongsToParent: belongsToParent ?? this.belongsToParent); } @@ -138,8 +142,10 @@ class BelongsToChildExplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "belongsToChildExplicit.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField BELONGSTOPARENT = QueryField( fieldName: "belongsToParent", @@ -160,7 +166,7 @@ class BelongsToChildExplicit extends Model { modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: BelongsToChildExplicit.BELONGSTOPARENT, isRequired: false, - targetName: "belongsToParentID", + targetNames: ["belongsToParentID"], ofModelName: (BelongsToParent).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( @@ -186,3 +192,41 @@ class _BelongsToChildExplicitModelType return BelongsToChildExplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [BelongsToChildExplicit] in your schema. +@immutable +class BelongsToChildExplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of BelongsToChildExplicitModelIdentifier using [id] the primary key. + const BelongsToChildExplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'BelongsToChildExplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is BelongsToChildExplicitModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/BelongsToChildImplicit.dart b/packages/amplify_datastore/example/lib/models/BelongsToChildImplicit.dart index 5f059c7dc8..417a73bd3d 100644 --- a/packages/amplify_datastore/example/lib/models/BelongsToChildImplicit.dart +++ b/packages/amplify_datastore/example/lib/models/BelongsToChildImplicit.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the BelongsToChildImplicit type in your schema. @@ -36,9 +36,13 @@ class BelongsToChildImplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + BelongsToChildImplicitModelIdentifier get modelIdentifier { + return BelongsToChildImplicitModelIdentifier(id: id); } String? get name { @@ -109,9 +113,9 @@ class BelongsToChildImplicit extends Model { } BelongsToChildImplicit copyWith( - {String? id, String? name, BelongsToParent? belongsToParent}) { + {String? name, BelongsToParent? belongsToParent}) { return BelongsToChildImplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, belongsToParent: belongsToParent ?? this.belongsToParent); } @@ -138,8 +142,10 @@ class BelongsToChildImplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "belongsToChildImplicit.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField BELONGSTOPARENT = QueryField( fieldName: "belongsToParent", @@ -160,7 +166,7 @@ class BelongsToChildImplicit extends Model { modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: BelongsToChildImplicit.BELONGSTOPARENT, isRequired: false, - targetName: "belongsToChildImplicitBelongsToParentId", + targetNames: ["belongsToChildImplicitBelongsToParentId"], ofModelName: (BelongsToParent).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( @@ -186,3 +192,41 @@ class _BelongsToChildImplicitModelType return BelongsToChildImplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [BelongsToChildImplicit] in your schema. +@immutable +class BelongsToChildImplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of BelongsToChildImplicitModelIdentifier using [id] the primary key. + const BelongsToChildImplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'BelongsToChildImplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is BelongsToChildImplicitModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/BelongsToParent.dart b/packages/amplify_datastore/example/lib/models/BelongsToParent.dart index 6eef03def2..3df0fa0f5b 100644 --- a/packages/amplify_datastore/example/lib/models/BelongsToParent.dart +++ b/packages/amplify_datastore/example/lib/models/BelongsToParent.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the BelongsToParent type in your schema. @@ -39,9 +39,13 @@ class BelongsToParent extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + BelongsToParentModelIdentifier get modelIdentifier { + return BelongsToParentModelIdentifier(id: id); } String? get name { @@ -150,14 +154,13 @@ class BelongsToParent extends Model { } BelongsToParent copyWith( - {String? id, - String? name, + {String? name, BelongsToChildImplicit? implicitChild, BelongsToChildExplicit? explicitChild, String? belongsToParentImplicitChildId, String? belongsToParentExplicitChildId}) { return BelongsToParent._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, implicitChild: implicitChild ?? this.implicitChild, explicitChild: explicitChild ?? this.explicitChild, @@ -200,7 +203,9 @@ class BelongsToParent extends Model { 'belongsToParentExplicitChildId': _belongsToParentExplicitChildId }; - static final QueryField ID = QueryField(fieldName: "belongsToParent.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField IMPLICITCHILD = QueryField( fieldName: "implicitChild", @@ -270,3 +275,41 @@ class _BelongsToParentModelType extends ModelType { return BelongsToParent.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [BelongsToParent] in your schema. +@immutable +class BelongsToParentModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of BelongsToParentModelIdentifier using [id] the primary key. + const BelongsToParentModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'BelongsToParentModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is BelongsToParentModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/Blog.dart b/packages/amplify_datastore/example/lib/models/Blog.dart index 95dd9b2c6d..4c4fbaf075 100644 --- a/packages/amplify_datastore/example/lib/models/Blog.dart +++ b/packages/amplify_datastore/example/lib/models/Blog.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,19 +37,23 @@ class Blog extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + BlogModelIdentifier get modelIdentifier { + return BlogModelIdentifier(id: id); } String get name { try { return _name!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -114,9 +118,9 @@ class Blog extends Model { return buffer.toString(); } - Blog copyWith({String? id, String? name, List? posts}) { + Blog copyWith({String? name, List? posts}) { return Blog._internal( - id: id ?? this.id, name: name ?? this.name, posts: posts ?? this.posts); + id: id, name: name ?? this.name, posts: posts ?? this.posts); } Blog.fromJson(Map json) @@ -144,7 +148,9 @@ class Blog extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "blog.id"); + static final QueryModelIdentifier MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField POSTS = QueryField( fieldName: "posts", @@ -190,3 +196,40 @@ class _BlogModelType extends ModelType { return Blog.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Blog] in your schema. +@immutable +class BlogModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of BlogModelIdentifier using [id] the primary key. + const BlogModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'BlogModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is BlogModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/Comment.dart b/packages/amplify_datastore/example/lib/models/Comment.dart index 067aea5ee5..84c5f733d9 100644 --- a/packages/amplify_datastore/example/lib/models/Comment.dart +++ b/packages/amplify_datastore/example/lib/models/Comment.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the Comment type in your schema. @@ -36,9 +36,13 @@ class Comment extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + CommentModelIdentifier get modelIdentifier { + return CommentModelIdentifier(id: id); } Post? get post { @@ -49,10 +53,10 @@ class Comment extends Model { try { return _content!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -112,11 +116,9 @@ class Comment extends Model { return buffer.toString(); } - Comment copyWith({String? id, Post? post, String? content}) { + Comment copyWith({Post? post, String? content}) { return Comment._internal( - id: id ?? this.id, - post: post ?? this.post, - content: content ?? this.content); + id: id, post: post ?? this.post, content: content ?? this.content); } Comment.fromJson(Map json) @@ -141,7 +143,9 @@ class Comment extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "comment.id"); + static final QueryModelIdentifier MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField POST = QueryField( fieldName: "post", fieldType: ModelFieldType(ModelFieldTypeEnum.model, @@ -152,12 +156,16 @@ class Comment extends Model { modelSchemaDefinition.name = "Comment"; modelSchemaDefinition.pluralName = "Comments"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["postID", "content"], name: "byPost") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: Comment.POST, isRequired: false, - targetName: "postID", + targetNames: ["postID"], ofModelName: (Post).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -187,3 +195,40 @@ class _CommentModelType extends ModelType { return Comment.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Comment] in your schema. +@immutable +class CommentModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of CommentModelIdentifier using [id] the primary key. + const CommentModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'CommentModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CommentModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalExplicit.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalExplicit.dart new file mode 100644 index 0000000000..db5d3ab080 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalExplicit.dart @@ -0,0 +1,267 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyChildBidirectionalExplicit type in your schema. +@immutable +class CpkHasManyChildBidirectionalExplicit extends Model { + static const classType = _CpkHasManyChildBidirectionalExplicitModelType(); + final String id; + final String? _name; + final CpkHasManyParentBidirectionalExplicit? _hasManyParent; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyChildBidirectionalExplicitModelIdentifier get modelIdentifier { + try { + return CpkHasManyChildBidirectionalExplicitModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkHasManyParentBidirectionalExplicit? get hasManyParent { + return _hasManyParent; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasManyChildBidirectionalExplicit._internal( + {required this.id, required name, hasManyParent, createdAt, updatedAt}) + : _name = name, + _hasManyParent = hasManyParent, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasManyChildBidirectionalExplicit( + {String? id, + required String name, + CpkHasManyParentBidirectionalExplicit? hasManyParent}) { + return CpkHasManyChildBidirectionalExplicit._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + hasManyParent: hasManyParent); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyChildBidirectionalExplicit && + id == other.id && + _name == other._name && + _hasManyParent == other._hasManyParent; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyChildBidirectionalExplicit {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("hasManyParent=" + + (_hasManyParent != null ? _hasManyParent!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyChildBidirectionalExplicit copyWith( + {CpkHasManyParentBidirectionalExplicit? hasManyParent}) { + return CpkHasManyChildBidirectionalExplicit._internal( + id: id, name: name, hasManyParent: hasManyParent ?? this.hasManyParent); + } + + CpkHasManyChildBidirectionalExplicit.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _hasManyParent = json['hasManyParent']?['serializedData'] != null + ? CpkHasManyParentBidirectionalExplicit.fromJson( + Map.from( + json['hasManyParent']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'hasManyParent': _hasManyParent?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkHasManyChildBidirectionalExplicitModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkHasManyChildBidirectionalExplicitModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField HASMANYPARENT = QueryField( + fieldName: "hasManyParent", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasManyParentBidirectionalExplicit).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyChildBidirectionalExplicit"; + modelSchemaDefinition.pluralName = "CpkHasManyChildBidirectionalExplicits"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null), + ModelIndex( + fields: const ["hasManyParentID", "hasManyParentName"], + name: "byHasManyParent") + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyChildBidirectionalExplicit.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkHasManyChildBidirectionalExplicit.HASMANYPARENT, + isRequired: false, + targetNames: ["hasManyParentID", "hasManyParentName"], + ofModelName: (CpkHasManyParentBidirectionalExplicit).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasManyChildBidirectionalExplicitModelType + extends ModelType { + const _CpkHasManyChildBidirectionalExplicitModelType(); + + @override + CpkHasManyChildBidirectionalExplicit fromJson(Map jsonData) { + return CpkHasManyChildBidirectionalExplicit.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyChildBidirectionalExplicit] in your schema. +@immutable +class CpkHasManyChildBidirectionalExplicitModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyChildBidirectionalExplicitModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyChildBidirectionalExplicitModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyChildBidirectionalExplicitModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyChildBidirectionalExplicitModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalImplicit.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalImplicit.dart new file mode 100644 index 0000000000..90e924d8c4 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyChildBidirectionalImplicit.dart @@ -0,0 +1,267 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyChildBidirectionalImplicit type in your schema. +@immutable +class CpkHasManyChildBidirectionalImplicit extends Model { + static const classType = _CpkHasManyChildBidirectionalImplicitModelType(); + final String id; + final String? _name; + final CpkHasManyParentBidirectionalImplicit? _hasManyParent; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyChildBidirectionalImplicitModelIdentifier get modelIdentifier { + try { + return CpkHasManyChildBidirectionalImplicitModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkHasManyParentBidirectionalImplicit? get hasManyParent { + return _hasManyParent; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasManyChildBidirectionalImplicit._internal( + {required this.id, required name, hasManyParent, createdAt, updatedAt}) + : _name = name, + _hasManyParent = hasManyParent, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasManyChildBidirectionalImplicit( + {String? id, + required String name, + CpkHasManyParentBidirectionalImplicit? hasManyParent}) { + return CpkHasManyChildBidirectionalImplicit._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + hasManyParent: hasManyParent); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyChildBidirectionalImplicit && + id == other.id && + _name == other._name && + _hasManyParent == other._hasManyParent; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyChildBidirectionalImplicit {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("hasManyParent=" + + (_hasManyParent != null ? _hasManyParent!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyChildBidirectionalImplicit copyWith( + {CpkHasManyParentBidirectionalImplicit? hasManyParent}) { + return CpkHasManyChildBidirectionalImplicit._internal( + id: id, name: name, hasManyParent: hasManyParent ?? this.hasManyParent); + } + + CpkHasManyChildBidirectionalImplicit.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _hasManyParent = json['hasManyParent']?['serializedData'] != null + ? CpkHasManyParentBidirectionalImplicit.fromJson( + Map.from( + json['hasManyParent']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'hasManyParent': _hasManyParent?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkHasManyChildBidirectionalImplicitModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkHasManyChildBidirectionalImplicitModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField HASMANYPARENT = QueryField( + fieldName: "hasManyParent", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasManyParentBidirectionalImplicit).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyChildBidirectionalImplicit"; + modelSchemaDefinition.pluralName = "CpkHasManyChildBidirectionalImplicits"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyChildBidirectionalImplicit.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkHasManyChildBidirectionalImplicit.HASMANYPARENT, + isRequired: false, + targetNames: [ + "cpkHasManyParentBidirectionalImplicitBidirectionalImplicitChildrenId", + "cpkHasManyParentBidirectionalImplicitBidirectionalImplicitChildrenName" + ], + ofModelName: (CpkHasManyParentBidirectionalImplicit).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasManyChildBidirectionalImplicitModelType + extends ModelType { + const _CpkHasManyChildBidirectionalImplicitModelType(); + + @override + CpkHasManyChildBidirectionalImplicit fromJson(Map jsonData) { + return CpkHasManyChildBidirectionalImplicit.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyChildBidirectionalImplicit] in your schema. +@immutable +class CpkHasManyChildBidirectionalImplicitModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyChildBidirectionalImplicitModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyChildBidirectionalImplicitModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyChildBidirectionalImplicitModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyChildBidirectionalImplicitModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalExplicit.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalExplicit.dart new file mode 100644 index 0000000000..374e7892de --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalExplicit.dart @@ -0,0 +1,284 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyParentBidirectionalExplicit type in your schema. +@immutable +class CpkHasManyParentBidirectionalExplicit extends Model { + static const classType = _CpkHasManyParentBidirectionalExplicitModelType(); + final String id; + final String? _name; + final List? + _bidirectionalExplicitChildren; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyParentBidirectionalExplicitModelIdentifier get modelIdentifier { + try { + return CpkHasManyParentBidirectionalExplicitModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + List? + get bidirectionalExplicitChildren { + return _bidirectionalExplicitChildren; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasManyParentBidirectionalExplicit._internal( + {required this.id, + required name, + bidirectionalExplicitChildren, + createdAt, + updatedAt}) + : _name = name, + _bidirectionalExplicitChildren = bidirectionalExplicitChildren, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasManyParentBidirectionalExplicit( + {String? id, + required String name, + List? + bidirectionalExplicitChildren}) { + return CpkHasManyParentBidirectionalExplicit._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + bidirectionalExplicitChildren: bidirectionalExplicitChildren != null + ? List.unmodifiable( + bidirectionalExplicitChildren) + : bidirectionalExplicitChildren); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyParentBidirectionalExplicit && + id == other.id && + _name == other._name && + DeepCollectionEquality().equals(_bidirectionalExplicitChildren, + other._bidirectionalExplicitChildren); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyParentBidirectionalExplicit {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyParentBidirectionalExplicit copyWith( + {List? + bidirectionalExplicitChildren}) { + return CpkHasManyParentBidirectionalExplicit._internal( + id: id, + name: name, + bidirectionalExplicitChildren: bidirectionalExplicitChildren ?? + this.bidirectionalExplicitChildren); + } + + CpkHasManyParentBidirectionalExplicit.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _bidirectionalExplicitChildren = + json['bidirectionalExplicitChildren'] is List + ? (json['bidirectionalExplicitChildren'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => CpkHasManyChildBidirectionalExplicit.fromJson( + Map.from(e['serializedData']))) + .toList() + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'bidirectionalExplicitChildren': _bidirectionalExplicitChildren + ?.map((CpkHasManyChildBidirectionalExplicit? e) => e?.toJson()) + .toList(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkHasManyParentBidirectionalExplicitModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkHasManyParentBidirectionalExplicitModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField BIDIRECTIONALEXPLICITCHILDREN = QueryField( + fieldName: "bidirectionalExplicitChildren", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasManyChildBidirectionalExplicit).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyParentBidirectionalExplicit"; + modelSchemaDefinition.pluralName = "CpkHasManyParentBidirectionalExplicits"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyParentBidirectionalExplicit.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: + CpkHasManyParentBidirectionalExplicit.BIDIRECTIONALEXPLICITCHILDREN, + isRequired: false, + ofModelName: (CpkHasManyChildBidirectionalExplicit).toString(), + associatedKey: CpkHasManyChildBidirectionalExplicit.HASMANYPARENT)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasManyParentBidirectionalExplicitModelType + extends ModelType { + const _CpkHasManyParentBidirectionalExplicitModelType(); + + @override + CpkHasManyParentBidirectionalExplicit fromJson( + Map jsonData) { + return CpkHasManyParentBidirectionalExplicit.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyParentBidirectionalExplicit] in your schema. +@immutable +class CpkHasManyParentBidirectionalExplicitModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyParentBidirectionalExplicitModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyParentBidirectionalExplicitModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyParentBidirectionalExplicitModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyParentBidirectionalExplicitModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalImplicit.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalImplicit.dart new file mode 100644 index 0000000000..5189804b2f --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyParentBidirectionalImplicit.dart @@ -0,0 +1,284 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyParentBidirectionalImplicit type in your schema. +@immutable +class CpkHasManyParentBidirectionalImplicit extends Model { + static const classType = _CpkHasManyParentBidirectionalImplicitModelType(); + final String id; + final String? _name; + final List? + _bidirectionalImplicitChildren; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyParentBidirectionalImplicitModelIdentifier get modelIdentifier { + try { + return CpkHasManyParentBidirectionalImplicitModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + List? + get bidirectionalImplicitChildren { + return _bidirectionalImplicitChildren; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasManyParentBidirectionalImplicit._internal( + {required this.id, + required name, + bidirectionalImplicitChildren, + createdAt, + updatedAt}) + : _name = name, + _bidirectionalImplicitChildren = bidirectionalImplicitChildren, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasManyParentBidirectionalImplicit( + {String? id, + required String name, + List? + bidirectionalImplicitChildren}) { + return CpkHasManyParentBidirectionalImplicit._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + bidirectionalImplicitChildren: bidirectionalImplicitChildren != null + ? List.unmodifiable( + bidirectionalImplicitChildren) + : bidirectionalImplicitChildren); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyParentBidirectionalImplicit && + id == other.id && + _name == other._name && + DeepCollectionEquality().equals(_bidirectionalImplicitChildren, + other._bidirectionalImplicitChildren); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyParentBidirectionalImplicit {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyParentBidirectionalImplicit copyWith( + {List? + bidirectionalImplicitChildren}) { + return CpkHasManyParentBidirectionalImplicit._internal( + id: id, + name: name, + bidirectionalImplicitChildren: bidirectionalImplicitChildren ?? + this.bidirectionalImplicitChildren); + } + + CpkHasManyParentBidirectionalImplicit.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _bidirectionalImplicitChildren = + json['bidirectionalImplicitChildren'] is List + ? (json['bidirectionalImplicitChildren'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => CpkHasManyChildBidirectionalImplicit.fromJson( + Map.from(e['serializedData']))) + .toList() + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'bidirectionalImplicitChildren': _bidirectionalImplicitChildren + ?.map((CpkHasManyChildBidirectionalImplicit? e) => e?.toJson()) + .toList(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkHasManyParentBidirectionalImplicitModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkHasManyParentBidirectionalImplicitModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField BIDIRECTIONALIMPLICITCHILDREN = QueryField( + fieldName: "bidirectionalImplicitChildren", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasManyChildBidirectionalImplicit).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyParentBidirectionalImplicit"; + modelSchemaDefinition.pluralName = "CpkHasManyParentBidirectionalImplicits"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyParentBidirectionalImplicit.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: + CpkHasManyParentBidirectionalImplicit.BIDIRECTIONALIMPLICITCHILDREN, + isRequired: false, + ofModelName: (CpkHasManyChildBidirectionalImplicit).toString(), + associatedKey: CpkHasManyChildBidirectionalImplicit.HASMANYPARENT)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasManyParentBidirectionalImplicitModelType + extends ModelType { + const _CpkHasManyParentBidirectionalImplicitModelType(); + + @override + CpkHasManyParentBidirectionalImplicit fromJson( + Map jsonData) { + return CpkHasManyParentBidirectionalImplicit.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyParentBidirectionalImplicit] in your schema. +@immutable +class CpkHasManyParentBidirectionalImplicitModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyParentBidirectionalImplicitModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyParentBidirectionalImplicitModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyParentBidirectionalImplicitModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyParentBidirectionalImplicitModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildExplicit.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildExplicit.dart new file mode 100644 index 0000000000..1dfeea93db --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildExplicit.dart @@ -0,0 +1,303 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyUnidirectionalChildExplicit type in your schema. +@immutable +class CpkHasManyUnidirectionalChildExplicit extends Model { + static const classType = _CpkHasManyUnidirectionalChildExplicitModelType(); + final String id; + final String? _name; + final String? _hasManyParentID; + final String? _hasManyParentName; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyUnidirectionalChildExplicitModelIdentifier get modelIdentifier { + try { + return CpkHasManyUnidirectionalChildExplicitModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get hasManyParentID { + try { + return _hasManyParentID!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get hasManyParentName { + try { + return _hasManyParentName!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasManyUnidirectionalChildExplicit._internal( + {required this.id, + required name, + required hasManyParentID, + required hasManyParentName, + createdAt, + updatedAt}) + : _name = name, + _hasManyParentID = hasManyParentID, + _hasManyParentName = hasManyParentName, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasManyUnidirectionalChildExplicit( + {String? id, + required String name, + required String hasManyParentID, + required String hasManyParentName}) { + return CpkHasManyUnidirectionalChildExplicit._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + hasManyParentID: hasManyParentID, + hasManyParentName: hasManyParentName); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyUnidirectionalChildExplicit && + id == other.id && + _name == other._name && + _hasManyParentID == other._hasManyParentID && + _hasManyParentName == other._hasManyParentName; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyUnidirectionalChildExplicit {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("hasManyParentID=" + "$_hasManyParentID" + ", "); + buffer.write("hasManyParentName=" + "$_hasManyParentName" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyUnidirectionalChildExplicit copyWith( + {String? hasManyParentID, String? hasManyParentName}) { + return CpkHasManyUnidirectionalChildExplicit._internal( + id: id, + name: name, + hasManyParentID: hasManyParentID ?? this.hasManyParentID, + hasManyParentName: hasManyParentName ?? this.hasManyParentName); + } + + CpkHasManyUnidirectionalChildExplicit.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _hasManyParentID = json['hasManyParentID'], + _hasManyParentName = json['hasManyParentName'], + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'hasManyParentID': _hasManyParentID, + 'hasManyParentName': _hasManyParentName, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkHasManyUnidirectionalChildExplicitModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkHasManyUnidirectionalChildExplicitModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField HASMANYPARENTID = + QueryField(fieldName: "hasManyParentID"); + static final QueryField HASMANYPARENTNAME = + QueryField(fieldName: "hasManyParentName"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyUnidirectionalChildExplicit"; + modelSchemaDefinition.pluralName = "CpkHasManyUnidirectionalChildExplicits"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null), + ModelIndex( + fields: const ["hasManyParentID", "hasManyParentName"], + name: "byHasManyParentCpk") + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalChildExplicit.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalChildExplicit.HASMANYPARENTID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalChildExplicit.HASMANYPARENTNAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasManyUnidirectionalChildExplicitModelType + extends ModelType { + const _CpkHasManyUnidirectionalChildExplicitModelType(); + + @override + CpkHasManyUnidirectionalChildExplicit fromJson( + Map jsonData) { + return CpkHasManyUnidirectionalChildExplicit.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyUnidirectionalChildExplicit] in your schema. +@immutable +class CpkHasManyUnidirectionalChildExplicitModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyUnidirectionalChildExplicitModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyUnidirectionalChildExplicitModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyUnidirectionalChildExplicitModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyUnidirectionalChildExplicitModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildImplicit.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildImplicit.dart new file mode 100644 index 0000000000..5fb0466084 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalChildImplicit.dart @@ -0,0 +1,304 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyUnidirectionalChildImplicit type in your schema. +@immutable +class CpkHasManyUnidirectionalChildImplicit extends Model { + static const classType = _CpkHasManyUnidirectionalChildImplicitModelType(); + final String id; + final String? _name; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + final String? _cpkHasManyUnidirectionalParentImplicitChildrenId; + final String? _cpkHasManyUnidirectionalParentImplicitChildrenName; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyUnidirectionalChildImplicitModelIdentifier get modelIdentifier { + try { + return CpkHasManyUnidirectionalChildImplicitModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + String? get cpkHasManyUnidirectionalParentImplicitChildrenId { + return _cpkHasManyUnidirectionalParentImplicitChildrenId; + } + + String? get cpkHasManyUnidirectionalParentImplicitChildrenName { + return _cpkHasManyUnidirectionalParentImplicitChildrenName; + } + + const CpkHasManyUnidirectionalChildImplicit._internal( + {required this.id, + required name, + createdAt, + updatedAt, + cpkHasManyUnidirectionalParentImplicitChildrenId, + cpkHasManyUnidirectionalParentImplicitChildrenName}) + : _name = name, + _createdAt = createdAt, + _updatedAt = updatedAt, + _cpkHasManyUnidirectionalParentImplicitChildrenId = + cpkHasManyUnidirectionalParentImplicitChildrenId, + _cpkHasManyUnidirectionalParentImplicitChildrenName = + cpkHasManyUnidirectionalParentImplicitChildrenName; + + factory CpkHasManyUnidirectionalChildImplicit( + {String? id, + required String name, + String? cpkHasManyUnidirectionalParentImplicitChildrenId, + String? cpkHasManyUnidirectionalParentImplicitChildrenName}) { + return CpkHasManyUnidirectionalChildImplicit._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + cpkHasManyUnidirectionalParentImplicitChildrenId: + cpkHasManyUnidirectionalParentImplicitChildrenId, + cpkHasManyUnidirectionalParentImplicitChildrenName: + cpkHasManyUnidirectionalParentImplicitChildrenName); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyUnidirectionalChildImplicit && + id == other.id && + _name == other._name && + _cpkHasManyUnidirectionalParentImplicitChildrenId == + other._cpkHasManyUnidirectionalParentImplicitChildrenId && + _cpkHasManyUnidirectionalParentImplicitChildrenName == + other._cpkHasManyUnidirectionalParentImplicitChildrenName; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyUnidirectionalChildImplicit {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write("updatedAt=" + + (_updatedAt != null ? _updatedAt!.format() : "null") + + ", "); + buffer.write("cpkHasManyUnidirectionalParentImplicitChildrenId=" + + "$_cpkHasManyUnidirectionalParentImplicitChildrenId" + + ", "); + buffer.write("cpkHasManyUnidirectionalParentImplicitChildrenName=" + + "$_cpkHasManyUnidirectionalParentImplicitChildrenName"); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyUnidirectionalChildImplicit copyWith( + {String? cpkHasManyUnidirectionalParentImplicitChildrenId, + String? cpkHasManyUnidirectionalParentImplicitChildrenName}) { + return CpkHasManyUnidirectionalChildImplicit._internal( + id: id, + name: name, + cpkHasManyUnidirectionalParentImplicitChildrenId: + cpkHasManyUnidirectionalParentImplicitChildrenId ?? + this.cpkHasManyUnidirectionalParentImplicitChildrenId, + cpkHasManyUnidirectionalParentImplicitChildrenName: + cpkHasManyUnidirectionalParentImplicitChildrenName ?? + this.cpkHasManyUnidirectionalParentImplicitChildrenName); + } + + CpkHasManyUnidirectionalChildImplicit.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null, + _cpkHasManyUnidirectionalParentImplicitChildrenId = + json['cpkHasManyUnidirectionalParentImplicitChildrenId'], + _cpkHasManyUnidirectionalParentImplicitChildrenName = + json['cpkHasManyUnidirectionalParentImplicitChildrenName']; + + Map toJson() => { + 'id': id, + 'name': _name, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format(), + 'cpkHasManyUnidirectionalParentImplicitChildrenId': + _cpkHasManyUnidirectionalParentImplicitChildrenId, + 'cpkHasManyUnidirectionalParentImplicitChildrenName': + _cpkHasManyUnidirectionalParentImplicitChildrenName + }; + + static final QueryModelIdentifier< + CpkHasManyUnidirectionalChildImplicitModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkHasManyUnidirectionalChildImplicitModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField CPKHASMANYUNIDIRECTIONALPARENTIMPLICITCHILDRENID = + QueryField(fieldName: "cpkHasManyUnidirectionalParentImplicitChildrenId"); + static final QueryField CPKHASMANYUNIDIRECTIONALPARENTIMPLICITCHILDRENNAME = + QueryField( + fieldName: "cpkHasManyUnidirectionalParentImplicitChildrenName"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyUnidirectionalChildImplicit"; + modelSchemaDefinition.pluralName = "CpkHasManyUnidirectionalChildImplicits"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalChildImplicit.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalChildImplicit + .CPKHASMANYUNIDIRECTIONALPARENTIMPLICITCHILDRENID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalChildImplicit + .CPKHASMANYUNIDIRECTIONALPARENTIMPLICITCHILDRENNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + }); +} + +class _CpkHasManyUnidirectionalChildImplicitModelType + extends ModelType { + const _CpkHasManyUnidirectionalChildImplicitModelType(); + + @override + CpkHasManyUnidirectionalChildImplicit fromJson( + Map jsonData) { + return CpkHasManyUnidirectionalChildImplicit.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyUnidirectionalChildImplicit] in your schema. +@immutable +class CpkHasManyUnidirectionalChildImplicitModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyUnidirectionalChildImplicitModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyUnidirectionalChildImplicitModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyUnidirectionalChildImplicitModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyUnidirectionalChildImplicitModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalParent.dart b/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalParent.dart new file mode 100644 index 0000000000..99fe7e0012 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasManyUnidirectionalParent.dart @@ -0,0 +1,312 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasManyUnidirectionalParent type in your schema. +@immutable +class CpkHasManyUnidirectionalParent extends Model { + static const classType = _CpkHasManyUnidirectionalParentModelType(); + final String id; + final String? _name; + final List? _implicitChildren; + final List? _explicitChildren; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasManyUnidirectionalParentModelIdentifier get modelIdentifier { + try { + return CpkHasManyUnidirectionalParentModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + List? get implicitChildren { + return _implicitChildren; + } + + List? get explicitChildren { + return _explicitChildren; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasManyUnidirectionalParent._internal( + {required this.id, + required name, + implicitChildren, + explicitChildren, + createdAt, + updatedAt}) + : _name = name, + _implicitChildren = implicitChildren, + _explicitChildren = explicitChildren, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasManyUnidirectionalParent( + {String? id, + required String name, + List? implicitChildren, + List? explicitChildren}) { + return CpkHasManyUnidirectionalParent._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + implicitChildren: implicitChildren != null + ? List.unmodifiable( + implicitChildren) + : implicitChildren, + explicitChildren: explicitChildren != null + ? List.unmodifiable( + explicitChildren) + : explicitChildren); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasManyUnidirectionalParent && + id == other.id && + _name == other._name && + DeepCollectionEquality() + .equals(_implicitChildren, other._implicitChildren) && + DeepCollectionEquality() + .equals(_explicitChildren, other._explicitChildren); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasManyUnidirectionalParent {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasManyUnidirectionalParent copyWith( + {List? implicitChildren, + List? explicitChildren}) { + return CpkHasManyUnidirectionalParent._internal( + id: id, + name: name, + implicitChildren: implicitChildren ?? this.implicitChildren, + explicitChildren: explicitChildren ?? this.explicitChildren); + } + + CpkHasManyUnidirectionalParent.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _implicitChildren = json['implicitChildren'] is List + ? (json['implicitChildren'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => CpkHasManyUnidirectionalChildImplicit.fromJson( + Map.from(e['serializedData']))) + .toList() + : null, + _explicitChildren = json['explicitChildren'] is List + ? (json['explicitChildren'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => CpkHasManyUnidirectionalChildExplicit.fromJson( + Map.from(e['serializedData']))) + .toList() + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'implicitChildren': _implicitChildren + ?.map((CpkHasManyUnidirectionalChildImplicit? e) => e?.toJson()) + .toList(), + 'explicitChildren': _explicitChildren + ?.map((CpkHasManyUnidirectionalChildExplicit? e) => e?.toJson()) + .toList(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkHasManyUnidirectionalParentModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField IMPLICITCHILDREN = QueryField( + fieldName: "implicitChildren", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasManyUnidirectionalChildImplicit).toString())); + static final QueryField EXPLICITCHILDREN = QueryField( + fieldName: "explicitChildren", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasManyUnidirectionalChildExplicit).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasManyUnidirectionalParent"; + modelSchemaDefinition.pluralName = "CpkHasManyUnidirectionalParents"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasManyUnidirectionalParent.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: CpkHasManyUnidirectionalParent.IMPLICITCHILDREN, + isRequired: false, + ofModelName: (CpkHasManyUnidirectionalChildImplicit).toString(), + associatedKey: CpkHasManyUnidirectionalChildImplicit + .CPKHASMANYUNIDIRECTIONALPARENTIMPLICITCHILDRENID)); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: CpkHasManyUnidirectionalParent.EXPLICITCHILDREN, + isRequired: false, + ofModelName: (CpkHasManyUnidirectionalChildExplicit).toString(), + associatedKey: CpkHasManyUnidirectionalChildExplicit.HASMANYPARENTID)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasManyUnidirectionalParentModelType + extends ModelType { + const _CpkHasManyUnidirectionalParentModelType(); + + @override + CpkHasManyUnidirectionalParent fromJson(Map jsonData) { + return CpkHasManyUnidirectionalParent.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasManyUnidirectionalParent] in your schema. +@immutable +class CpkHasManyUnidirectionalParentModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasManyUnidirectionalParentModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasManyUnidirectionalParentModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasManyUnidirectionalParentModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasManyUnidirectionalParentModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalChild.dart b/packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalChild.dart new file mode 100644 index 0000000000..d76af7cd95 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalChild.dart @@ -0,0 +1,228 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasOneUnidirectionalChild type in your schema. +@immutable +class CpkHasOneUnidirectionalChild extends Model { + static const classType = _CpkHasOneUnidirectionalChildModelType(); + final String id; + final String? _name; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasOneUnidirectionalChildModelIdentifier get modelIdentifier { + try { + return CpkHasOneUnidirectionalChildModelIdentifier(id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkHasOneUnidirectionalChild._internal( + {required this.id, required name, createdAt, updatedAt}) + : _name = name, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkHasOneUnidirectionalChild({String? id, required String name}) { + return CpkHasOneUnidirectionalChild._internal( + id: id == null ? UUID.getUUID() : id, name: name); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasOneUnidirectionalChild && + id == other.id && + _name == other._name; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasOneUnidirectionalChild {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasOneUnidirectionalChild copyWith() { + return CpkHasOneUnidirectionalChild._internal(id: id, name: name); + } + + CpkHasOneUnidirectionalChild.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasOneUnidirectionalChild"; + modelSchemaDefinition.pluralName = "CpkHasOneUnidirectionalChildren"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasOneUnidirectionalChild.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkHasOneUnidirectionalChildModelType + extends ModelType { + const _CpkHasOneUnidirectionalChildModelType(); + + @override + CpkHasOneUnidirectionalChild fromJson(Map jsonData) { + return CpkHasOneUnidirectionalChild.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasOneUnidirectionalChild] in your schema. +@immutable +class CpkHasOneUnidirectionalChildModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasOneUnidirectionalChildModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasOneUnidirectionalChildModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasOneUnidirectionalChildModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasOneUnidirectionalChildModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalParent.dart b/packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalParent.dart new file mode 100644 index 0000000000..164ed812d5 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkHasOneUnidirectionalParent.dart @@ -0,0 +1,399 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkHasOneUnidirectionalParent type in your schema. +@immutable +class CpkHasOneUnidirectionalParent extends Model { + static const classType = _CpkHasOneUnidirectionalParentModelType(); + final String id; + final String? _name; + final CpkHasOneUnidirectionalChild? _implicitChild; + final String? _explicitChildID; + final String? _explicitChildName; + final CpkHasOneUnidirectionalChild? _explicitChild; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + final String? _cpkHasOneUnidirectionalParentImplicitChildId; + final String? _cpkHasOneUnidirectionalParentImplicitChildName; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkHasOneUnidirectionalParentModelIdentifier get modelIdentifier { + try { + return CpkHasOneUnidirectionalParentModelIdentifier(id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkHasOneUnidirectionalChild? get implicitChild { + return _implicitChild; + } + + String? get explicitChildID { + return _explicitChildID; + } + + String? get explicitChildName { + return _explicitChildName; + } + + CpkHasOneUnidirectionalChild? get explicitChild { + return _explicitChild; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + String? get cpkHasOneUnidirectionalParentImplicitChildId { + return _cpkHasOneUnidirectionalParentImplicitChildId; + } + + String? get cpkHasOneUnidirectionalParentImplicitChildName { + return _cpkHasOneUnidirectionalParentImplicitChildName; + } + + const CpkHasOneUnidirectionalParent._internal( + {required this.id, + required name, + implicitChild, + explicitChildID, + explicitChildName, + explicitChild, + createdAt, + updatedAt, + cpkHasOneUnidirectionalParentImplicitChildId, + cpkHasOneUnidirectionalParentImplicitChildName}) + : _name = name, + _implicitChild = implicitChild, + _explicitChildID = explicitChildID, + _explicitChildName = explicitChildName, + _explicitChild = explicitChild, + _createdAt = createdAt, + _updatedAt = updatedAt, + _cpkHasOneUnidirectionalParentImplicitChildId = + cpkHasOneUnidirectionalParentImplicitChildId, + _cpkHasOneUnidirectionalParentImplicitChildName = + cpkHasOneUnidirectionalParentImplicitChildName; + + factory CpkHasOneUnidirectionalParent( + {String? id, + required String name, + CpkHasOneUnidirectionalChild? implicitChild, + String? explicitChildID, + String? explicitChildName, + CpkHasOneUnidirectionalChild? explicitChild, + String? cpkHasOneUnidirectionalParentImplicitChildId, + String? cpkHasOneUnidirectionalParentImplicitChildName}) { + return CpkHasOneUnidirectionalParent._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + implicitChild: implicitChild, + explicitChildID: explicitChildID, + explicitChildName: explicitChildName, + explicitChild: explicitChild, + cpkHasOneUnidirectionalParentImplicitChildId: + cpkHasOneUnidirectionalParentImplicitChildId, + cpkHasOneUnidirectionalParentImplicitChildName: + cpkHasOneUnidirectionalParentImplicitChildName); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkHasOneUnidirectionalParent && + id == other.id && + _name == other._name && + _implicitChild == other._implicitChild && + _explicitChildID == other._explicitChildID && + _explicitChildName == other._explicitChildName && + _explicitChild == other._explicitChild && + _cpkHasOneUnidirectionalParentImplicitChildId == + other._cpkHasOneUnidirectionalParentImplicitChildId && + _cpkHasOneUnidirectionalParentImplicitChildName == + other._cpkHasOneUnidirectionalParentImplicitChildName; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkHasOneUnidirectionalParent {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("explicitChildID=" + "$_explicitChildID" + ", "); + buffer.write("explicitChildName=" + "$_explicitChildName" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write("updatedAt=" + + (_updatedAt != null ? _updatedAt!.format() : "null") + + ", "); + buffer.write("cpkHasOneUnidirectionalParentImplicitChildId=" + + "$_cpkHasOneUnidirectionalParentImplicitChildId" + + ", "); + buffer.write("cpkHasOneUnidirectionalParentImplicitChildName=" + + "$_cpkHasOneUnidirectionalParentImplicitChildName"); + buffer.write("}"); + + return buffer.toString(); + } + + CpkHasOneUnidirectionalParent copyWith( + {CpkHasOneUnidirectionalChild? implicitChild, + String? explicitChildID, + String? explicitChildName, + CpkHasOneUnidirectionalChild? explicitChild, + String? cpkHasOneUnidirectionalParentImplicitChildId, + String? cpkHasOneUnidirectionalParentImplicitChildName}) { + return CpkHasOneUnidirectionalParent._internal( + id: id, + name: name, + implicitChild: implicitChild ?? this.implicitChild, + explicitChildID: explicitChildID ?? this.explicitChildID, + explicitChildName: explicitChildName ?? this.explicitChildName, + explicitChild: explicitChild ?? this.explicitChild, + cpkHasOneUnidirectionalParentImplicitChildId: + cpkHasOneUnidirectionalParentImplicitChildId ?? + this.cpkHasOneUnidirectionalParentImplicitChildId, + cpkHasOneUnidirectionalParentImplicitChildName: + cpkHasOneUnidirectionalParentImplicitChildName ?? + this.cpkHasOneUnidirectionalParentImplicitChildName); + } + + CpkHasOneUnidirectionalParent.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _implicitChild = json['implicitChild']?['serializedData'] != null + ? CpkHasOneUnidirectionalChild.fromJson(Map.from( + json['implicitChild']['serializedData'])) + : null, + _explicitChildID = json['explicitChildID'], + _explicitChildName = json['explicitChildName'], + _explicitChild = json['explicitChild']?['serializedData'] != null + ? CpkHasOneUnidirectionalChild.fromJson(Map.from( + json['explicitChild']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null, + _cpkHasOneUnidirectionalParentImplicitChildId = + json['cpkHasOneUnidirectionalParentImplicitChildId'], + _cpkHasOneUnidirectionalParentImplicitChildName = + json['cpkHasOneUnidirectionalParentImplicitChildName']; + + Map toJson() => { + 'id': id, + 'name': _name, + 'implicitChild': _implicitChild?.toJson(), + 'explicitChildID': _explicitChildID, + 'explicitChildName': _explicitChildName, + 'explicitChild': _explicitChild?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format(), + 'cpkHasOneUnidirectionalParentImplicitChildId': + _cpkHasOneUnidirectionalParentImplicitChildId, + 'cpkHasOneUnidirectionalParentImplicitChildName': + _cpkHasOneUnidirectionalParentImplicitChildName + }; + + static final QueryModelIdentifier< + CpkHasOneUnidirectionalParentModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField IMPLICITCHILD = QueryField( + fieldName: "implicitChild", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasOneUnidirectionalChild).toString())); + static final QueryField EXPLICITCHILDID = + QueryField(fieldName: "explicitChildID"); + static final QueryField EXPLICITCHILDNAME = + QueryField(fieldName: "explicitChildName"); + static final QueryField EXPLICITCHILD = QueryField( + fieldName: "explicitChild", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkHasOneUnidirectionalChild).toString())); + static final QueryField CPKHASONEUNIDIRECTIONALPARENTIMPLICITCHILDID = + QueryField(fieldName: "cpkHasOneUnidirectionalParentImplicitChildId"); + static final QueryField CPKHASONEUNIDIRECTIONALPARENTIMPLICITCHILDNAME = + QueryField(fieldName: "cpkHasOneUnidirectionalParentImplicitChildName"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkHasOneUnidirectionalParent"; + modelSchemaDefinition.pluralName = "CpkHasOneUnidirectionalParents"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasOneUnidirectionalParent.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasOne( + key: CpkHasOneUnidirectionalParent.IMPLICITCHILD, + isRequired: false, + ofModelName: (CpkHasOneUnidirectionalChild).toString(), + associatedKey: CpkHasOneUnidirectionalChild.ID)); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasOneUnidirectionalParent.EXPLICITCHILDID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasOneUnidirectionalParent.EXPLICITCHILDNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasOne( + key: CpkHasOneUnidirectionalParent.EXPLICITCHILD, + isRequired: false, + ofModelName: (CpkHasOneUnidirectionalChild).toString(), + associatedKey: CpkHasOneUnidirectionalChild.ID)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasOneUnidirectionalParent + .CPKHASONEUNIDIRECTIONALPARENTIMPLICITCHILDID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkHasOneUnidirectionalParent + .CPKHASONEUNIDIRECTIONALPARENTIMPLICITCHILDNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + }); +} + +class _CpkHasOneUnidirectionalParentModelType + extends ModelType { + const _CpkHasOneUnidirectionalParentModelType(); + + @override + CpkHasOneUnidirectionalParent fromJson(Map jsonData) { + return CpkHasOneUnidirectionalParent.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkHasOneUnidirectionalParent] in your schema. +@immutable +class CpkHasOneUnidirectionalParentModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkHasOneUnidirectionalParentModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkHasOneUnidirectionalParentModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkHasOneUnidirectionalParentModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkHasOneUnidirectionalParentModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkInventory.dart b/packages/amplify_datastore/example/lib/models/CpkInventory.dart new file mode 100644 index 0000000000..6da8f922ea --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkInventory.dart @@ -0,0 +1,311 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkInventory type in your schema. +@immutable +class CpkInventory extends Model { + static const classType = _CpkInventoryModelType(); + final String? _productId; + final String? _productName; + final String? _warehouseId; + final String? _description; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => modelIdentifier.serializeAsString(); + + CpkInventoryModelIdentifier get modelIdentifier { + try { + return CpkInventoryModelIdentifier( + productId: _productId!, + productName: _productName!, + warehouseId: _warehouseId!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get productId { + try { + return _productId!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get productName { + try { + return _productName!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get warehouseId { + try { + return _warehouseId!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String? get description { + return _description; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkInventory._internal( + {required productId, + required productName, + required warehouseId, + description, + createdAt, + updatedAt}) + : _productId = productId, + _productName = productName, + _warehouseId = warehouseId, + _description = description, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkInventory( + {required String productId, + required String productName, + required String warehouseId, + String? description}) { + return CpkInventory._internal( + productId: productId, + productName: productName, + warehouseId: warehouseId, + description: description); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkInventory && + _productId == other._productId && + _productName == other._productName && + _warehouseId == other._warehouseId && + _description == other._description; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkInventory {"); + buffer.write("productId=" + "$_productId" + ", "); + buffer.write("productName=" + "$_productName" + ", "); + buffer.write("warehouseId=" + "$_warehouseId" + ", "); + buffer.write("description=" + "$_description" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkInventory copyWith({String? description}) { + return CpkInventory._internal( + productId: productId, + productName: productName, + warehouseId: warehouseId, + description: description ?? this.description); + } + + CpkInventory.fromJson(Map json) + : _productId = json['productId'], + _productName = json['productName'], + _warehouseId = json['warehouseId'], + _description = json['description'], + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'productId': _productId, + 'productName': _productName, + 'warehouseId': _warehouseId, + 'description': _description, + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField PRODUCTID = QueryField(fieldName: "productId"); + static final QueryField PRODUCTNAME = QueryField(fieldName: "productName"); + static final QueryField WAREHOUSEID = QueryField(fieldName: "warehouseId"); + static final QueryField DESCRIPTION = QueryField(fieldName: "description"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkInventory"; + modelSchemaDefinition.pluralName = "CpkInventories"; + + modelSchemaDefinition.indexes = [ + ModelIndex( + fields: const ["productId", "productName", "warehouseId"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkInventory.PRODUCTID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkInventory.PRODUCTNAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkInventory.WAREHOUSEID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkInventory.DESCRIPTION, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkInventoryModelType extends ModelType { + const _CpkInventoryModelType(); + + @override + CpkInventory fromJson(Map jsonData) { + return CpkInventory.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkInventory] in your schema. +@immutable +class CpkInventoryModelIdentifier implements ModelIdentifier { + final String productId; + final String productName; + final String warehouseId; + + /// Create an instance of CpkInventoryModelIdentifier using [productId] the primary key. + /// And [productName], [warehouseId] the sort keys. + const CpkInventoryModelIdentifier( + {required this.productId, + required this.productName, + required this.warehouseId}); + + @override + Map serializeAsMap() => ({ + 'productId': productId, + 'productName': productName, + 'warehouseId': warehouseId + }); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkInventoryModelIdentifier(productId: $productId, productName: $productName, warehouseId: $warehouseId)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkInventoryModelIdentifier && + productId == other.productId && + productName == other.productName && + warehouseId == other.warehouseId; + } + + @override + int get hashCode => + productId.hashCode ^ productName.hashCode ^ warehouseId.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkManyToManyPost.dart b/packages/amplify_datastore/example/lib/models/CpkManyToManyPost.dart new file mode 100644 index 0000000000..dea8245a62 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkManyToManyPost.dart @@ -0,0 +1,238 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkManyToManyPost type in your schema. +@immutable +class CpkManyToManyPost extends Model { + static const classType = _CpkManyToManyPostModelType(); + final String id; + final String? _title; + final List? _tags; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkManyToManyPostModelIdentifier get modelIdentifier { + return CpkManyToManyPostModelIdentifier(id: id); + } + + String get title { + try { + return _title!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + List? get tags { + return _tags; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkManyToManyPost._internal( + {required this.id, required title, tags, createdAt, updatedAt}) + : _title = title, + _tags = tags, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkManyToManyPost( + {String? id, required String title, List? tags}) { + return CpkManyToManyPost._internal( + id: id == null ? UUID.getUUID() : id, + title: title, + tags: tags != null ? List.unmodifiable(tags) : tags); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkManyToManyPost && + id == other.id && + _title == other._title && + DeepCollectionEquality().equals(_tags, other._tags); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkManyToManyPost {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("title=" + "$_title" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkManyToManyPost copyWith({String? title, List? tags}) { + return CpkManyToManyPost._internal( + id: id, title: title ?? this.title, tags: tags ?? this.tags); + } + + CpkManyToManyPost.fromJson(Map json) + : id = json['id'], + _title = json['title'], + _tags = json['tags'] is List + ? (json['tags'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => CpkPostTags.fromJson( + Map.from(e['serializedData']))) + .toList() + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'title': _title, + 'tags': _tags?.map((CpkPostTags? e) => e?.toJson()).toList(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField TITLE = QueryField(fieldName: "title"); + static final QueryField TAGS = QueryField( + fieldName: "tags", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkPostTags).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkManyToManyPost"; + modelSchemaDefinition.pluralName = "CpkManyToManyPosts"; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkManyToManyPost.TITLE, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: CpkManyToManyPost.TAGS, + isRequired: false, + ofModelName: (CpkPostTags).toString(), + associatedKey: CpkPostTags.CPKMANYTOMANYPOST)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkManyToManyPostModelType extends ModelType { + const _CpkManyToManyPostModelType(); + + @override + CpkManyToManyPost fromJson(Map jsonData) { + return CpkManyToManyPost.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkManyToManyPost] in your schema. +@immutable +class CpkManyToManyPostModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of CpkManyToManyPostModelIdentifier using [id] the primary key. + const CpkManyToManyPostModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'CpkManyToManyPostModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkManyToManyPostModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkManyToManyTag.dart b/packages/amplify_datastore/example/lib/models/CpkManyToManyTag.dart new file mode 100644 index 0000000000..69b80b8aad --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkManyToManyTag.dart @@ -0,0 +1,258 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkManyToManyTag type in your schema. +@immutable +class CpkManyToManyTag extends Model { + static const classType = _CpkManyToManyTagModelType(); + final String id; + final String? _label; + final List? _posts; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkManyToManyTagModelIdentifier get modelIdentifier { + try { + return CpkManyToManyTagModelIdentifier(id: id, label: _label!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get label { + try { + return _label!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + List? get posts { + return _posts; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkManyToManyTag._internal( + {required this.id, required label, posts, createdAt, updatedAt}) + : _label = label, + _posts = posts, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkManyToManyTag( + {String? id, required String label, List? posts}) { + return CpkManyToManyTag._internal( + id: id == null ? UUID.getUUID() : id, + label: label, + posts: posts != null ? List.unmodifiable(posts) : posts); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkManyToManyTag && + id == other.id && + _label == other._label && + DeepCollectionEquality().equals(_posts, other._posts); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkManyToManyTag {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("label=" + "$_label" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkManyToManyTag copyWith({List? posts}) { + return CpkManyToManyTag._internal( + id: id, label: label, posts: posts ?? this.posts); + } + + CpkManyToManyTag.fromJson(Map json) + : id = json['id'], + _label = json['label'], + _posts = json['posts'] is List + ? (json['posts'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => CpkPostTags.fromJson( + Map.from(e['serializedData']))) + .toList() + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'label': _label, + 'posts': _posts?.map((CpkPostTags? e) => e?.toJson()).toList(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField LABEL = QueryField(fieldName: "label"); + static final QueryField POSTS = QueryField( + fieldName: "posts", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkPostTags).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkManyToManyTag"; + modelSchemaDefinition.pluralName = "CpkManyToManyTags"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "label"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkManyToManyTag.LABEL, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: CpkManyToManyTag.POSTS, + isRequired: false, + ofModelName: (CpkPostTags).toString(), + associatedKey: CpkPostTags.CPKMANYTOMANYTAG)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkManyToManyTagModelType extends ModelType { + const _CpkManyToManyTagModelType(); + + @override + CpkManyToManyTag fromJson(Map jsonData) { + return CpkManyToManyTag.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkManyToManyTag] in your schema. +@immutable +class CpkManyToManyTagModelIdentifier + implements ModelIdentifier { + final String id; + final String label; + + /// Create an instance of CpkManyToManyTagModelIdentifier using [id] the primary key. + /// And [label] the sort key. + const CpkManyToManyTagModelIdentifier( + {required this.id, required this.label}); + + @override + Map serializeAsMap() => + ({'id': id, 'label': label}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkManyToManyTagModelIdentifier(id: $id, label: $label)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkManyToManyTagModelIdentifier && + id == other.id && + label == other.label; + } + + @override + int get hashCode => id.hashCode ^ label.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitCD.dart b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitCD.dart new file mode 100644 index 0000000000..1ec96ec2c7 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitCD.dart @@ -0,0 +1,268 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkOneToOneBidirectionalChildExplicitCD type in your schema. +@immutable +class CpkOneToOneBidirectionalChildExplicitCD extends Model { + static const classType = _CpkOneToOneBidirectionalChildExplicitCDModelType(); + final String id; + final String? _name; + final CpkOneToOneBidirectionalParentCD? _belongsToParent; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkOneToOneBidirectionalChildExplicitCDModelIdentifier get modelIdentifier { + try { + return CpkOneToOneBidirectionalChildExplicitCDModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkOneToOneBidirectionalParentCD? get belongsToParent { + return _belongsToParent; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkOneToOneBidirectionalChildExplicitCD._internal( + {required this.id, required name, belongsToParent, createdAt, updatedAt}) + : _name = name, + _belongsToParent = belongsToParent, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkOneToOneBidirectionalChildExplicitCD( + {String? id, + required String name, + CpkOneToOneBidirectionalParentCD? belongsToParent}) { + return CpkOneToOneBidirectionalChildExplicitCD._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + belongsToParent: belongsToParent); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkOneToOneBidirectionalChildExplicitCD && + id == other.id && + _name == other._name && + _belongsToParent == other._belongsToParent; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkOneToOneBidirectionalChildExplicitCD {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("belongsToParent=" + + (_belongsToParent != null ? _belongsToParent!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkOneToOneBidirectionalChildExplicitCD copyWith( + {CpkOneToOneBidirectionalParentCD? belongsToParent}) { + return CpkOneToOneBidirectionalChildExplicitCD._internal( + id: id, + name: name, + belongsToParent: belongsToParent ?? this.belongsToParent); + } + + CpkOneToOneBidirectionalChildExplicitCD.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _belongsToParent = json['belongsToParent']?['serializedData'] != null + ? CpkOneToOneBidirectionalParentCD.fromJson( + Map.from( + json['belongsToParent']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'belongsToParent': _belongsToParent?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkOneToOneBidirectionalChildExplicitCDModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkOneToOneBidirectionalChildExplicitCDModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField BELONGSTOPARENT = QueryField( + fieldName: "belongsToParent", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalParentCD).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkOneToOneBidirectionalChildExplicitCD"; + modelSchemaDefinition.pluralName = + "CpkOneToOneBidirectionalChildExplicitCDS"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalChildExplicitCD.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkOneToOneBidirectionalChildExplicitCD.BELONGSTOPARENT, + isRequired: false, + targetNames: ["belongsToParentID", "belongsToParentName"], + ofModelName: (CpkOneToOneBidirectionalParentCD).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkOneToOneBidirectionalChildExplicitCDModelType + extends ModelType { + const _CpkOneToOneBidirectionalChildExplicitCDModelType(); + + @override + CpkOneToOneBidirectionalChildExplicitCD fromJson( + Map jsonData) { + return CpkOneToOneBidirectionalChildExplicitCD.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkOneToOneBidirectionalChildExplicitCD] in your schema. +@immutable +class CpkOneToOneBidirectionalChildExplicitCDModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkOneToOneBidirectionalChildExplicitCDModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkOneToOneBidirectionalChildExplicitCDModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkOneToOneBidirectionalChildExplicitCDModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkOneToOneBidirectionalChildExplicitCDModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitID.dart b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitID.dart new file mode 100644 index 0000000000..da1f59c325 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildExplicitID.dart @@ -0,0 +1,268 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkOneToOneBidirectionalChildExplicitID type in your schema. +@immutable +class CpkOneToOneBidirectionalChildExplicitID extends Model { + static const classType = _CpkOneToOneBidirectionalChildExplicitIDModelType(); + final String id; + final String? _name; + final CpkOneToOneBidirectionalParentID? _belongsToParent; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkOneToOneBidirectionalChildExplicitIDModelIdentifier get modelIdentifier { + try { + return CpkOneToOneBidirectionalChildExplicitIDModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkOneToOneBidirectionalParentID? get belongsToParent { + return _belongsToParent; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkOneToOneBidirectionalChildExplicitID._internal( + {required this.id, required name, belongsToParent, createdAt, updatedAt}) + : _name = name, + _belongsToParent = belongsToParent, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkOneToOneBidirectionalChildExplicitID( + {String? id, + required String name, + CpkOneToOneBidirectionalParentID? belongsToParent}) { + return CpkOneToOneBidirectionalChildExplicitID._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + belongsToParent: belongsToParent); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkOneToOneBidirectionalChildExplicitID && + id == other.id && + _name == other._name && + _belongsToParent == other._belongsToParent; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkOneToOneBidirectionalChildExplicitID {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("belongsToParent=" + + (_belongsToParent != null ? _belongsToParent!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkOneToOneBidirectionalChildExplicitID copyWith( + {CpkOneToOneBidirectionalParentID? belongsToParent}) { + return CpkOneToOneBidirectionalChildExplicitID._internal( + id: id, + name: name, + belongsToParent: belongsToParent ?? this.belongsToParent); + } + + CpkOneToOneBidirectionalChildExplicitID.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _belongsToParent = json['belongsToParent']?['serializedData'] != null + ? CpkOneToOneBidirectionalParentID.fromJson( + Map.from( + json['belongsToParent']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'belongsToParent': _belongsToParent?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkOneToOneBidirectionalChildExplicitIDModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkOneToOneBidirectionalChildExplicitIDModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField BELONGSTOPARENT = QueryField( + fieldName: "belongsToParent", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalParentID).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkOneToOneBidirectionalChildExplicitID"; + modelSchemaDefinition.pluralName = + "CpkOneToOneBidirectionalChildExplicitIDS"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalChildExplicitID.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkOneToOneBidirectionalChildExplicitID.BELONGSTOPARENT, + isRequired: false, + targetNames: ["belongsToParentID", "belongsToParentName"], + ofModelName: (CpkOneToOneBidirectionalParentID).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkOneToOneBidirectionalChildExplicitIDModelType + extends ModelType { + const _CpkOneToOneBidirectionalChildExplicitIDModelType(); + + @override + CpkOneToOneBidirectionalChildExplicitID fromJson( + Map jsonData) { + return CpkOneToOneBidirectionalChildExplicitID.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkOneToOneBidirectionalChildExplicitID] in your schema. +@immutable +class CpkOneToOneBidirectionalChildExplicitIDModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkOneToOneBidirectionalChildExplicitIDModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkOneToOneBidirectionalChildExplicitIDModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkOneToOneBidirectionalChildExplicitIDModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkOneToOneBidirectionalChildExplicitIDModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitCD.dart b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitCD.dart new file mode 100644 index 0000000000..f1cbf40c7c --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitCD.dart @@ -0,0 +1,271 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkOneToOneBidirectionalChildImplicitCD type in your schema. +@immutable +class CpkOneToOneBidirectionalChildImplicitCD extends Model { + static const classType = _CpkOneToOneBidirectionalChildImplicitCDModelType(); + final String id; + final String? _name; + final CpkOneToOneBidirectionalParentCD? _belongsToParent; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkOneToOneBidirectionalChildImplicitCDModelIdentifier get modelIdentifier { + try { + return CpkOneToOneBidirectionalChildImplicitCDModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkOneToOneBidirectionalParentCD? get belongsToParent { + return _belongsToParent; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkOneToOneBidirectionalChildImplicitCD._internal( + {required this.id, required name, belongsToParent, createdAt, updatedAt}) + : _name = name, + _belongsToParent = belongsToParent, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkOneToOneBidirectionalChildImplicitCD( + {String? id, + required String name, + CpkOneToOneBidirectionalParentCD? belongsToParent}) { + return CpkOneToOneBidirectionalChildImplicitCD._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + belongsToParent: belongsToParent); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkOneToOneBidirectionalChildImplicitCD && + id == other.id && + _name == other._name && + _belongsToParent == other._belongsToParent; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkOneToOneBidirectionalChildImplicitCD {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("belongsToParent=" + + (_belongsToParent != null ? _belongsToParent!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkOneToOneBidirectionalChildImplicitCD copyWith( + {CpkOneToOneBidirectionalParentCD? belongsToParent}) { + return CpkOneToOneBidirectionalChildImplicitCD._internal( + id: id, + name: name, + belongsToParent: belongsToParent ?? this.belongsToParent); + } + + CpkOneToOneBidirectionalChildImplicitCD.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _belongsToParent = json['belongsToParent']?['serializedData'] != null + ? CpkOneToOneBidirectionalParentCD.fromJson( + Map.from( + json['belongsToParent']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'belongsToParent': _belongsToParent?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkOneToOneBidirectionalChildImplicitCDModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkOneToOneBidirectionalChildImplicitCDModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField BELONGSTOPARENT = QueryField( + fieldName: "belongsToParent", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalParentCD).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkOneToOneBidirectionalChildImplicitCD"; + modelSchemaDefinition.pluralName = + "CpkOneToOneBidirectionalChildImplicitCDS"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalChildImplicitCD.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkOneToOneBidirectionalChildImplicitCD.BELONGSTOPARENT, + isRequired: false, + targetNames: [ + "cpkOneToOneBidirectionalChildImplicitCDBelongsToParentCustomId", + "cpkOneToOneBidirectionalChildImplicitCDBelongsToParentName" + ], + ofModelName: (CpkOneToOneBidirectionalParentCD).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkOneToOneBidirectionalChildImplicitCDModelType + extends ModelType { + const _CpkOneToOneBidirectionalChildImplicitCDModelType(); + + @override + CpkOneToOneBidirectionalChildImplicitCD fromJson( + Map jsonData) { + return CpkOneToOneBidirectionalChildImplicitCD.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkOneToOneBidirectionalChildImplicitCD] in your schema. +@immutable +class CpkOneToOneBidirectionalChildImplicitCDModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkOneToOneBidirectionalChildImplicitCDModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkOneToOneBidirectionalChildImplicitCDModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkOneToOneBidirectionalChildImplicitCDModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkOneToOneBidirectionalChildImplicitCDModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitID.dart b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitID.dart new file mode 100644 index 0000000000..3f6bb6687f --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalChildImplicitID.dart @@ -0,0 +1,271 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkOneToOneBidirectionalChildImplicitID type in your schema. +@immutable +class CpkOneToOneBidirectionalChildImplicitID extends Model { + static const classType = _CpkOneToOneBidirectionalChildImplicitIDModelType(); + final String id; + final String? _name; + final CpkOneToOneBidirectionalParentID? _belongsToParent; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkOneToOneBidirectionalChildImplicitIDModelIdentifier get modelIdentifier { + try { + return CpkOneToOneBidirectionalChildImplicitIDModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkOneToOneBidirectionalParentID? get belongsToParent { + return _belongsToParent; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkOneToOneBidirectionalChildImplicitID._internal( + {required this.id, required name, belongsToParent, createdAt, updatedAt}) + : _name = name, + _belongsToParent = belongsToParent, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkOneToOneBidirectionalChildImplicitID( + {String? id, + required String name, + CpkOneToOneBidirectionalParentID? belongsToParent}) { + return CpkOneToOneBidirectionalChildImplicitID._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + belongsToParent: belongsToParent); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkOneToOneBidirectionalChildImplicitID && + id == other.id && + _name == other._name && + _belongsToParent == other._belongsToParent; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkOneToOneBidirectionalChildImplicitID {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("belongsToParent=" + + (_belongsToParent != null ? _belongsToParent!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkOneToOneBidirectionalChildImplicitID copyWith( + {CpkOneToOneBidirectionalParentID? belongsToParent}) { + return CpkOneToOneBidirectionalChildImplicitID._internal( + id: id, + name: name, + belongsToParent: belongsToParent ?? this.belongsToParent); + } + + CpkOneToOneBidirectionalChildImplicitID.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _belongsToParent = json['belongsToParent']?['serializedData'] != null + ? CpkOneToOneBidirectionalParentID.fromJson( + Map.from( + json['belongsToParent']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'name': _name, + 'belongsToParent': _belongsToParent?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier< + CpkOneToOneBidirectionalChildImplicitIDModelIdentifier> + MODEL_IDENTIFIER = QueryModelIdentifier< + CpkOneToOneBidirectionalChildImplicitIDModelIdentifier>(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField BELONGSTOPARENT = QueryField( + fieldName: "belongsToParent", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalParentID).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkOneToOneBidirectionalChildImplicitID"; + modelSchemaDefinition.pluralName = + "CpkOneToOneBidirectionalChildImplicitIDS"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalChildImplicitID.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkOneToOneBidirectionalChildImplicitID.BELONGSTOPARENT, + isRequired: false, + targetNames: [ + "cpkOneToOneBidirectionalChildImplicitIDBelongsToParentId", + "cpkOneToOneBidirectionalChildImplicitIDBelongsToParentName" + ], + ofModelName: (CpkOneToOneBidirectionalParentID).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkOneToOneBidirectionalChildImplicitIDModelType + extends ModelType { + const _CpkOneToOneBidirectionalChildImplicitIDModelType(); + + @override + CpkOneToOneBidirectionalChildImplicitID fromJson( + Map jsonData) { + return CpkOneToOneBidirectionalChildImplicitID.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkOneToOneBidirectionalChildImplicitID] in your schema. +@immutable +class CpkOneToOneBidirectionalChildImplicitIDModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkOneToOneBidirectionalChildImplicitIDModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkOneToOneBidirectionalChildImplicitIDModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkOneToOneBidirectionalChildImplicitIDModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkOneToOneBidirectionalChildImplicitIDModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentCD.dart b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentCD.dart new file mode 100644 index 0000000000..0b40b1232f --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentCD.dart @@ -0,0 +1,443 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkOneToOneBidirectionalParentCD type in your schema. +@immutable +class CpkOneToOneBidirectionalParentCD extends Model { + static const classType = _CpkOneToOneBidirectionalParentCDModelType(); + final String? _customId; + final String? _name; + final CpkOneToOneBidirectionalChildImplicitCD? _implicitChild; + final CpkOneToOneBidirectionalChildExplicitCD? _explicitChild; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + final String? _cpkOneToOneBidirectionalParentCDImplicitChildId; + final String? _cpkOneToOneBidirectionalParentCDImplicitChildName; + final String? _cpkOneToOneBidirectionalParentCDExplicitChildId; + final String? _cpkOneToOneBidirectionalParentCDExplicitChildName; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => modelIdentifier.serializeAsString(); + + CpkOneToOneBidirectionalParentCDModelIdentifier get modelIdentifier { + try { + return CpkOneToOneBidirectionalParentCDModelIdentifier( + customId: _customId!, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get customId { + try { + return _customId!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkOneToOneBidirectionalChildImplicitCD? get implicitChild { + return _implicitChild; + } + + CpkOneToOneBidirectionalChildExplicitCD? get explicitChild { + return _explicitChild; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + String? get cpkOneToOneBidirectionalParentCDImplicitChildId { + return _cpkOneToOneBidirectionalParentCDImplicitChildId; + } + + String? get cpkOneToOneBidirectionalParentCDImplicitChildName { + return _cpkOneToOneBidirectionalParentCDImplicitChildName; + } + + String? get cpkOneToOneBidirectionalParentCDExplicitChildId { + return _cpkOneToOneBidirectionalParentCDExplicitChildId; + } + + String? get cpkOneToOneBidirectionalParentCDExplicitChildName { + return _cpkOneToOneBidirectionalParentCDExplicitChildName; + } + + const CpkOneToOneBidirectionalParentCD._internal( + {required customId, + required name, + implicitChild, + explicitChild, + createdAt, + updatedAt, + cpkOneToOneBidirectionalParentCDImplicitChildId, + cpkOneToOneBidirectionalParentCDImplicitChildName, + cpkOneToOneBidirectionalParentCDExplicitChildId, + cpkOneToOneBidirectionalParentCDExplicitChildName}) + : _customId = customId, + _name = name, + _implicitChild = implicitChild, + _explicitChild = explicitChild, + _createdAt = createdAt, + _updatedAt = updatedAt, + _cpkOneToOneBidirectionalParentCDImplicitChildId = + cpkOneToOneBidirectionalParentCDImplicitChildId, + _cpkOneToOneBidirectionalParentCDImplicitChildName = + cpkOneToOneBidirectionalParentCDImplicitChildName, + _cpkOneToOneBidirectionalParentCDExplicitChildId = + cpkOneToOneBidirectionalParentCDExplicitChildId, + _cpkOneToOneBidirectionalParentCDExplicitChildName = + cpkOneToOneBidirectionalParentCDExplicitChildName; + + factory CpkOneToOneBidirectionalParentCD( + {required String customId, + required String name, + CpkOneToOneBidirectionalChildImplicitCD? implicitChild, + CpkOneToOneBidirectionalChildExplicitCD? explicitChild, + String? cpkOneToOneBidirectionalParentCDImplicitChildId, + String? cpkOneToOneBidirectionalParentCDImplicitChildName, + String? cpkOneToOneBidirectionalParentCDExplicitChildId, + String? cpkOneToOneBidirectionalParentCDExplicitChildName}) { + return CpkOneToOneBidirectionalParentCD._internal( + customId: customId, + name: name, + implicitChild: implicitChild, + explicitChild: explicitChild, + cpkOneToOneBidirectionalParentCDImplicitChildId: + cpkOneToOneBidirectionalParentCDImplicitChildId, + cpkOneToOneBidirectionalParentCDImplicitChildName: + cpkOneToOneBidirectionalParentCDImplicitChildName, + cpkOneToOneBidirectionalParentCDExplicitChildId: + cpkOneToOneBidirectionalParentCDExplicitChildId, + cpkOneToOneBidirectionalParentCDExplicitChildName: + cpkOneToOneBidirectionalParentCDExplicitChildName); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkOneToOneBidirectionalParentCD && + _customId == other._customId && + _name == other._name && + _implicitChild == other._implicitChild && + _explicitChild == other._explicitChild && + _cpkOneToOneBidirectionalParentCDImplicitChildId == + other._cpkOneToOneBidirectionalParentCDImplicitChildId && + _cpkOneToOneBidirectionalParentCDImplicitChildName == + other._cpkOneToOneBidirectionalParentCDImplicitChildName && + _cpkOneToOneBidirectionalParentCDExplicitChildId == + other._cpkOneToOneBidirectionalParentCDExplicitChildId && + _cpkOneToOneBidirectionalParentCDExplicitChildName == + other._cpkOneToOneBidirectionalParentCDExplicitChildName; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkOneToOneBidirectionalParentCD {"); + buffer.write("customId=" + "$_customId" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write("updatedAt=" + + (_updatedAt != null ? _updatedAt!.format() : "null") + + ", "); + buffer.write("cpkOneToOneBidirectionalParentCDImplicitChildId=" + + "$_cpkOneToOneBidirectionalParentCDImplicitChildId" + + ", "); + buffer.write("cpkOneToOneBidirectionalParentCDImplicitChildName=" + + "$_cpkOneToOneBidirectionalParentCDImplicitChildName" + + ", "); + buffer.write("cpkOneToOneBidirectionalParentCDExplicitChildId=" + + "$_cpkOneToOneBidirectionalParentCDExplicitChildId" + + ", "); + buffer.write("cpkOneToOneBidirectionalParentCDExplicitChildName=" + + "$_cpkOneToOneBidirectionalParentCDExplicitChildName"); + buffer.write("}"); + + return buffer.toString(); + } + + CpkOneToOneBidirectionalParentCD copyWith( + {CpkOneToOneBidirectionalChildImplicitCD? implicitChild, + CpkOneToOneBidirectionalChildExplicitCD? explicitChild, + String? cpkOneToOneBidirectionalParentCDImplicitChildId, + String? cpkOneToOneBidirectionalParentCDImplicitChildName, + String? cpkOneToOneBidirectionalParentCDExplicitChildId, + String? cpkOneToOneBidirectionalParentCDExplicitChildName}) { + return CpkOneToOneBidirectionalParentCD._internal( + customId: customId, + name: name, + implicitChild: implicitChild ?? this.implicitChild, + explicitChild: explicitChild ?? this.explicitChild, + cpkOneToOneBidirectionalParentCDImplicitChildId: + cpkOneToOneBidirectionalParentCDImplicitChildId ?? + this.cpkOneToOneBidirectionalParentCDImplicitChildId, + cpkOneToOneBidirectionalParentCDImplicitChildName: + cpkOneToOneBidirectionalParentCDImplicitChildName ?? + this.cpkOneToOneBidirectionalParentCDImplicitChildName, + cpkOneToOneBidirectionalParentCDExplicitChildId: + cpkOneToOneBidirectionalParentCDExplicitChildId ?? + this.cpkOneToOneBidirectionalParentCDExplicitChildId, + cpkOneToOneBidirectionalParentCDExplicitChildName: + cpkOneToOneBidirectionalParentCDExplicitChildName ?? + this.cpkOneToOneBidirectionalParentCDExplicitChildName); + } + + CpkOneToOneBidirectionalParentCD.fromJson(Map json) + : _customId = json['customId'], + _name = json['name'], + _implicitChild = json['implicitChild']?['serializedData'] != null + ? CpkOneToOneBidirectionalChildImplicitCD.fromJson( + Map.from( + json['implicitChild']['serializedData'])) + : null, + _explicitChild = json['explicitChild']?['serializedData'] != null + ? CpkOneToOneBidirectionalChildExplicitCD.fromJson( + Map.from( + json['explicitChild']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null, + _cpkOneToOneBidirectionalParentCDImplicitChildId = + json['cpkOneToOneBidirectionalParentCDImplicitChildId'], + _cpkOneToOneBidirectionalParentCDImplicitChildName = + json['cpkOneToOneBidirectionalParentCDImplicitChildName'], + _cpkOneToOneBidirectionalParentCDExplicitChildId = + json['cpkOneToOneBidirectionalParentCDExplicitChildId'], + _cpkOneToOneBidirectionalParentCDExplicitChildName = + json['cpkOneToOneBidirectionalParentCDExplicitChildName']; + + Map toJson() => { + 'customId': _customId, + 'name': _name, + 'implicitChild': _implicitChild?.toJson(), + 'explicitChild': _explicitChild?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format(), + 'cpkOneToOneBidirectionalParentCDImplicitChildId': + _cpkOneToOneBidirectionalParentCDImplicitChildId, + 'cpkOneToOneBidirectionalParentCDImplicitChildName': + _cpkOneToOneBidirectionalParentCDImplicitChildName, + 'cpkOneToOneBidirectionalParentCDExplicitChildId': + _cpkOneToOneBidirectionalParentCDExplicitChildId, + 'cpkOneToOneBidirectionalParentCDExplicitChildName': + _cpkOneToOneBidirectionalParentCDExplicitChildName + }; + + static final QueryModelIdentifier< + CpkOneToOneBidirectionalParentCDModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField CUSTOMID = QueryField(fieldName: "customId"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField IMPLICITCHILD = QueryField( + fieldName: "implicitChild", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalChildImplicitCD).toString())); + static final QueryField EXPLICITCHILD = QueryField( + fieldName: "explicitChild", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalChildExplicitCD).toString())); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTCDIMPLICITCHILDID = + QueryField(fieldName: "cpkOneToOneBidirectionalParentCDImplicitChildId"); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTCDIMPLICITCHILDNAME = + QueryField( + fieldName: "cpkOneToOneBidirectionalParentCDImplicitChildName"); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTCDEXPLICITCHILDID = + QueryField(fieldName: "cpkOneToOneBidirectionalParentCDExplicitChildId"); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTCDEXPLICITCHILDNAME = + QueryField( + fieldName: "cpkOneToOneBidirectionalParentCDExplicitChildName"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkOneToOneBidirectionalParentCD"; + modelSchemaDefinition.pluralName = "CpkOneToOneBidirectionalParentCDS"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["customId", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentCD.CUSTOMID, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentCD.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasOne( + key: CpkOneToOneBidirectionalParentCD.IMPLICITCHILD, + isRequired: false, + ofModelName: (CpkOneToOneBidirectionalChildImplicitCD).toString(), + associatedKey: + CpkOneToOneBidirectionalChildImplicitCD.BELONGSTOPARENT)); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasOne( + key: CpkOneToOneBidirectionalParentCD.EXPLICITCHILD, + isRequired: false, + ofModelName: (CpkOneToOneBidirectionalChildExplicitCD).toString(), + associatedKey: + CpkOneToOneBidirectionalChildExplicitCD.BELONGSTOPARENT)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentCD + .CPKONETOONEBIDIRECTIONALPARENTCDIMPLICITCHILDID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentCD + .CPKONETOONEBIDIRECTIONALPARENTCDIMPLICITCHILDNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentCD + .CPKONETOONEBIDIRECTIONALPARENTCDEXPLICITCHILDID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentCD + .CPKONETOONEBIDIRECTIONALPARENTCDEXPLICITCHILDNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + }); +} + +class _CpkOneToOneBidirectionalParentCDModelType + extends ModelType { + const _CpkOneToOneBidirectionalParentCDModelType(); + + @override + CpkOneToOneBidirectionalParentCD fromJson(Map jsonData) { + return CpkOneToOneBidirectionalParentCD.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkOneToOneBidirectionalParentCD] in your schema. +@immutable +class CpkOneToOneBidirectionalParentCDModelIdentifier + implements ModelIdentifier { + final String customId; + final String name; + + /// Create an instance of CpkOneToOneBidirectionalParentCDModelIdentifier using [customId] the primary key. + /// And [name] the sort key. + const CpkOneToOneBidirectionalParentCDModelIdentifier( + {required this.customId, required this.name}); + + @override + Map serializeAsMap() => + ({'customId': customId, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkOneToOneBidirectionalParentCDModelIdentifier(customId: $customId, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkOneToOneBidirectionalParentCDModelIdentifier && + customId == other.customId && + name == other.name; + } + + @override + int get hashCode => customId.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentID.dart b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentID.dart new file mode 100644 index 0000000000..b8e5a618b5 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkOneToOneBidirectionalParentID.dart @@ -0,0 +1,426 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkOneToOneBidirectionalParentID type in your schema. +@immutable +class CpkOneToOneBidirectionalParentID extends Model { + static const classType = _CpkOneToOneBidirectionalParentIDModelType(); + final String id; + final String? _name; + final CpkOneToOneBidirectionalChildImplicitID? _implicitChild; + final CpkOneToOneBidirectionalChildExplicitID? _explicitChild; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + final String? _cpkOneToOneBidirectionalParentIDImplicitChildId; + final String? _cpkOneToOneBidirectionalParentIDImplicitChildName; + final String? _cpkOneToOneBidirectionalParentIDExplicitChildId; + final String? _cpkOneToOneBidirectionalParentIDExplicitChildName; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkOneToOneBidirectionalParentIDModelIdentifier get modelIdentifier { + try { + return CpkOneToOneBidirectionalParentIDModelIdentifier( + id: id, name: _name!); + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + String get name { + try { + return _name!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkOneToOneBidirectionalChildImplicitID? get implicitChild { + return _implicitChild; + } + + CpkOneToOneBidirectionalChildExplicitID? get explicitChild { + return _explicitChild; + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + String? get cpkOneToOneBidirectionalParentIDImplicitChildId { + return _cpkOneToOneBidirectionalParentIDImplicitChildId; + } + + String? get cpkOneToOneBidirectionalParentIDImplicitChildName { + return _cpkOneToOneBidirectionalParentIDImplicitChildName; + } + + String? get cpkOneToOneBidirectionalParentIDExplicitChildId { + return _cpkOneToOneBidirectionalParentIDExplicitChildId; + } + + String? get cpkOneToOneBidirectionalParentIDExplicitChildName { + return _cpkOneToOneBidirectionalParentIDExplicitChildName; + } + + const CpkOneToOneBidirectionalParentID._internal( + {required this.id, + required name, + implicitChild, + explicitChild, + createdAt, + updatedAt, + cpkOneToOneBidirectionalParentIDImplicitChildId, + cpkOneToOneBidirectionalParentIDImplicitChildName, + cpkOneToOneBidirectionalParentIDExplicitChildId, + cpkOneToOneBidirectionalParentIDExplicitChildName}) + : _name = name, + _implicitChild = implicitChild, + _explicitChild = explicitChild, + _createdAt = createdAt, + _updatedAt = updatedAt, + _cpkOneToOneBidirectionalParentIDImplicitChildId = + cpkOneToOneBidirectionalParentIDImplicitChildId, + _cpkOneToOneBidirectionalParentIDImplicitChildName = + cpkOneToOneBidirectionalParentIDImplicitChildName, + _cpkOneToOneBidirectionalParentIDExplicitChildId = + cpkOneToOneBidirectionalParentIDExplicitChildId, + _cpkOneToOneBidirectionalParentIDExplicitChildName = + cpkOneToOneBidirectionalParentIDExplicitChildName; + + factory CpkOneToOneBidirectionalParentID( + {String? id, + required String name, + CpkOneToOneBidirectionalChildImplicitID? implicitChild, + CpkOneToOneBidirectionalChildExplicitID? explicitChild, + String? cpkOneToOneBidirectionalParentIDImplicitChildId, + String? cpkOneToOneBidirectionalParentIDImplicitChildName, + String? cpkOneToOneBidirectionalParentIDExplicitChildId, + String? cpkOneToOneBidirectionalParentIDExplicitChildName}) { + return CpkOneToOneBidirectionalParentID._internal( + id: id == null ? UUID.getUUID() : id, + name: name, + implicitChild: implicitChild, + explicitChild: explicitChild, + cpkOneToOneBidirectionalParentIDImplicitChildId: + cpkOneToOneBidirectionalParentIDImplicitChildId, + cpkOneToOneBidirectionalParentIDImplicitChildName: + cpkOneToOneBidirectionalParentIDImplicitChildName, + cpkOneToOneBidirectionalParentIDExplicitChildId: + cpkOneToOneBidirectionalParentIDExplicitChildId, + cpkOneToOneBidirectionalParentIDExplicitChildName: + cpkOneToOneBidirectionalParentIDExplicitChildName); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkOneToOneBidirectionalParentID && + id == other.id && + _name == other._name && + _implicitChild == other._implicitChild && + _explicitChild == other._explicitChild && + _cpkOneToOneBidirectionalParentIDImplicitChildId == + other._cpkOneToOneBidirectionalParentIDImplicitChildId && + _cpkOneToOneBidirectionalParentIDImplicitChildName == + other._cpkOneToOneBidirectionalParentIDImplicitChildName && + _cpkOneToOneBidirectionalParentIDExplicitChildId == + other._cpkOneToOneBidirectionalParentIDExplicitChildId && + _cpkOneToOneBidirectionalParentIDExplicitChildName == + other._cpkOneToOneBidirectionalParentIDExplicitChildName; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkOneToOneBidirectionalParentID {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("name=" + "$_name" + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write("updatedAt=" + + (_updatedAt != null ? _updatedAt!.format() : "null") + + ", "); + buffer.write("cpkOneToOneBidirectionalParentIDImplicitChildId=" + + "$_cpkOneToOneBidirectionalParentIDImplicitChildId" + + ", "); + buffer.write("cpkOneToOneBidirectionalParentIDImplicitChildName=" + + "$_cpkOneToOneBidirectionalParentIDImplicitChildName" + + ", "); + buffer.write("cpkOneToOneBidirectionalParentIDExplicitChildId=" + + "$_cpkOneToOneBidirectionalParentIDExplicitChildId" + + ", "); + buffer.write("cpkOneToOneBidirectionalParentIDExplicitChildName=" + + "$_cpkOneToOneBidirectionalParentIDExplicitChildName"); + buffer.write("}"); + + return buffer.toString(); + } + + CpkOneToOneBidirectionalParentID copyWith( + {CpkOneToOneBidirectionalChildImplicitID? implicitChild, + CpkOneToOneBidirectionalChildExplicitID? explicitChild, + String? cpkOneToOneBidirectionalParentIDImplicitChildId, + String? cpkOneToOneBidirectionalParentIDImplicitChildName, + String? cpkOneToOneBidirectionalParentIDExplicitChildId, + String? cpkOneToOneBidirectionalParentIDExplicitChildName}) { + return CpkOneToOneBidirectionalParentID._internal( + id: id, + name: name, + implicitChild: implicitChild ?? this.implicitChild, + explicitChild: explicitChild ?? this.explicitChild, + cpkOneToOneBidirectionalParentIDImplicitChildId: + cpkOneToOneBidirectionalParentIDImplicitChildId ?? + this.cpkOneToOneBidirectionalParentIDImplicitChildId, + cpkOneToOneBidirectionalParentIDImplicitChildName: + cpkOneToOneBidirectionalParentIDImplicitChildName ?? + this.cpkOneToOneBidirectionalParentIDImplicitChildName, + cpkOneToOneBidirectionalParentIDExplicitChildId: + cpkOneToOneBidirectionalParentIDExplicitChildId ?? + this.cpkOneToOneBidirectionalParentIDExplicitChildId, + cpkOneToOneBidirectionalParentIDExplicitChildName: + cpkOneToOneBidirectionalParentIDExplicitChildName ?? + this.cpkOneToOneBidirectionalParentIDExplicitChildName); + } + + CpkOneToOneBidirectionalParentID.fromJson(Map json) + : id = json['id'], + _name = json['name'], + _implicitChild = json['implicitChild']?['serializedData'] != null + ? CpkOneToOneBidirectionalChildImplicitID.fromJson( + Map.from( + json['implicitChild']['serializedData'])) + : null, + _explicitChild = json['explicitChild']?['serializedData'] != null + ? CpkOneToOneBidirectionalChildExplicitID.fromJson( + Map.from( + json['explicitChild']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null, + _cpkOneToOneBidirectionalParentIDImplicitChildId = + json['cpkOneToOneBidirectionalParentIDImplicitChildId'], + _cpkOneToOneBidirectionalParentIDImplicitChildName = + json['cpkOneToOneBidirectionalParentIDImplicitChildName'], + _cpkOneToOneBidirectionalParentIDExplicitChildId = + json['cpkOneToOneBidirectionalParentIDExplicitChildId'], + _cpkOneToOneBidirectionalParentIDExplicitChildName = + json['cpkOneToOneBidirectionalParentIDExplicitChildName']; + + Map toJson() => { + 'id': id, + 'name': _name, + 'implicitChild': _implicitChild?.toJson(), + 'explicitChild': _explicitChild?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format(), + 'cpkOneToOneBidirectionalParentIDImplicitChildId': + _cpkOneToOneBidirectionalParentIDImplicitChildId, + 'cpkOneToOneBidirectionalParentIDImplicitChildName': + _cpkOneToOneBidirectionalParentIDImplicitChildName, + 'cpkOneToOneBidirectionalParentIDExplicitChildId': + _cpkOneToOneBidirectionalParentIDExplicitChildId, + 'cpkOneToOneBidirectionalParentIDExplicitChildName': + _cpkOneToOneBidirectionalParentIDExplicitChildName + }; + + static final QueryModelIdentifier< + CpkOneToOneBidirectionalParentIDModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField NAME = QueryField(fieldName: "name"); + static final QueryField IMPLICITCHILD = QueryField( + fieldName: "implicitChild", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalChildImplicitID).toString())); + static final QueryField EXPLICITCHILD = QueryField( + fieldName: "explicitChild", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkOneToOneBidirectionalChildExplicitID).toString())); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTIDIMPLICITCHILDID = + QueryField(fieldName: "cpkOneToOneBidirectionalParentIDImplicitChildId"); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTIDIMPLICITCHILDNAME = + QueryField( + fieldName: "cpkOneToOneBidirectionalParentIDImplicitChildName"); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTIDEXPLICITCHILDID = + QueryField(fieldName: "cpkOneToOneBidirectionalParentIDExplicitChildId"); + static final QueryField CPKONETOONEBIDIRECTIONALPARENTIDEXPLICITCHILDNAME = + QueryField( + fieldName: "cpkOneToOneBidirectionalParentIDExplicitChildName"); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkOneToOneBidirectionalParentID"; + modelSchemaDefinition.pluralName = "CpkOneToOneBidirectionalParentIDS"; + + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id", "name"], name: null) + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentID.NAME, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasOne( + key: CpkOneToOneBidirectionalParentID.IMPLICITCHILD, + isRequired: false, + ofModelName: (CpkOneToOneBidirectionalChildImplicitID).toString(), + associatedKey: + CpkOneToOneBidirectionalChildImplicitID.BELONGSTOPARENT)); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasOne( + key: CpkOneToOneBidirectionalParentID.EXPLICITCHILD, + isRequired: false, + ofModelName: (CpkOneToOneBidirectionalChildExplicitID).toString(), + associatedKey: + CpkOneToOneBidirectionalChildExplicitID.BELONGSTOPARENT)); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentID + .CPKONETOONEBIDIRECTIONALPARENTIDIMPLICITCHILDID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentID + .CPKONETOONEBIDIRECTIONALPARENTIDIMPLICITCHILDNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentID + .CPKONETOONEBIDIRECTIONALPARENTIDEXPLICITCHILDID, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: CpkOneToOneBidirectionalParentID + .CPKONETOONEBIDIRECTIONALPARENTIDEXPLICITCHILDNAME, + isRequired: false, + ofType: ModelFieldType(ModelFieldTypeEnum.string))); + }); +} + +class _CpkOneToOneBidirectionalParentIDModelType + extends ModelType { + const _CpkOneToOneBidirectionalParentIDModelType(); + + @override + CpkOneToOneBidirectionalParentID fromJson(Map jsonData) { + return CpkOneToOneBidirectionalParentID.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkOneToOneBidirectionalParentID] in your schema. +@immutable +class CpkOneToOneBidirectionalParentIDModelIdentifier + implements ModelIdentifier { + final String id; + final String name; + + /// Create an instance of CpkOneToOneBidirectionalParentIDModelIdentifier using [id] the primary key. + /// And [name] the sort key. + const CpkOneToOneBidirectionalParentIDModelIdentifier( + {required this.id, required this.name}); + + @override + Map serializeAsMap() => + ({'id': id, 'name': name}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'CpkOneToOneBidirectionalParentIDModelIdentifier(id: $id, name: $name)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkOneToOneBidirectionalParentIDModelIdentifier && + id == other.id && + name == other.name; + } + + @override + int get hashCode => id.hashCode ^ name.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CpkPostTags.dart b/packages/amplify_datastore/example/lib/models/CpkPostTags.dart new file mode 100644 index 0000000000..8a30489d40 --- /dev/null +++ b/packages/amplify_datastore/example/lib/models/CpkPostTags.dart @@ -0,0 +1,272 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:flutter/foundation.dart'; + +/// This is an auto generated class representing the CpkPostTags type in your schema. +@immutable +class CpkPostTags extends Model { + static const classType = _CpkPostTagsModelType(); + final String id; + final CpkManyToManyPost? _cpkManyToManyPost; + final CpkManyToManyTag? _cpkManyToManyTag; + final TemporalDateTime? _createdAt; + final TemporalDateTime? _updatedAt; + + @override + getInstanceType() => classType; + + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') + @override + String getId() => id; + + CpkPostTagsModelIdentifier get modelIdentifier { + return CpkPostTagsModelIdentifier(id: id); + } + + CpkManyToManyPost get cpkManyToManyPost { + try { + return _cpkManyToManyPost!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + CpkManyToManyTag get cpkManyToManyTag { + try { + return _cpkManyToManyTag!; + } catch (e) { + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages + .codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: AmplifyExceptionMessages + .codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString()); + } + } + + TemporalDateTime? get createdAt { + return _createdAt; + } + + TemporalDateTime? get updatedAt { + return _updatedAt; + } + + const CpkPostTags._internal( + {required this.id, + required cpkManyToManyPost, + required cpkManyToManyTag, + createdAt, + updatedAt}) + : _cpkManyToManyPost = cpkManyToManyPost, + _cpkManyToManyTag = cpkManyToManyTag, + _createdAt = createdAt, + _updatedAt = updatedAt; + + factory CpkPostTags( + {String? id, + required CpkManyToManyPost cpkManyToManyPost, + required CpkManyToManyTag cpkManyToManyTag}) { + return CpkPostTags._internal( + id: id == null ? UUID.getUUID() : id, + cpkManyToManyPost: cpkManyToManyPost, + cpkManyToManyTag: cpkManyToManyTag); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is CpkPostTags && + id == other.id && + _cpkManyToManyPost == other._cpkManyToManyPost && + _cpkManyToManyTag == other._cpkManyToManyTag; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = StringBuffer(); + + buffer.write("CpkPostTags {"); + buffer.write("id=" + "$id" + ", "); + buffer.write("cpkManyToManyPost=" + + (_cpkManyToManyPost != null ? _cpkManyToManyPost!.toString() : "null") + + ", "); + buffer.write("cpkManyToManyTag=" + + (_cpkManyToManyTag != null ? _cpkManyToManyTag!.toString() : "null") + + ", "); + buffer.write("createdAt=" + + (_createdAt != null ? _createdAt!.format() : "null") + + ", "); + buffer.write( + "updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null")); + buffer.write("}"); + + return buffer.toString(); + } + + CpkPostTags copyWith( + {CpkManyToManyPost? cpkManyToManyPost, + CpkManyToManyTag? cpkManyToManyTag}) { + return CpkPostTags._internal( + id: id, + cpkManyToManyPost: cpkManyToManyPost ?? this.cpkManyToManyPost, + cpkManyToManyTag: cpkManyToManyTag ?? this.cpkManyToManyTag); + } + + CpkPostTags.fromJson(Map json) + : id = json['id'], + _cpkManyToManyPost = + json['cpkManyToManyPost']?['serializedData'] != null + ? CpkManyToManyPost.fromJson(Map.from( + json['cpkManyToManyPost']['serializedData'])) + : null, + _cpkManyToManyTag = json['cpkManyToManyTag']?['serializedData'] != null + ? CpkManyToManyTag.fromJson(Map.from( + json['cpkManyToManyTag']['serializedData'])) + : null, + _createdAt = json['createdAt'] != null + ? TemporalDateTime.fromString(json['createdAt']) + : null, + _updatedAt = json['updatedAt'] != null + ? TemporalDateTime.fromString(json['updatedAt']) + : null; + + Map toJson() => { + 'id': id, + 'cpkManyToManyPost': _cpkManyToManyPost?.toJson(), + 'cpkManyToManyTag': _cpkManyToManyTag?.toJson(), + 'createdAt': _createdAt?.format(), + 'updatedAt': _updatedAt?.format() + }; + + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); + static final QueryField CPKMANYTOMANYPOST = QueryField( + fieldName: "cpkManyToManyPost", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkManyToManyPost).toString())); + static final QueryField CPKMANYTOMANYTAG = QueryField( + fieldName: "cpkManyToManyTag", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, + ofModelName: (CpkManyToManyTag).toString())); + static var schema = + Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = "CpkPostTags"; + modelSchemaDefinition.pluralName = "CpkPostTags"; + + modelSchemaDefinition.indexes = [ + ModelIndex( + fields: const ["cpkManyToManyPostID"], name: "byCpkManyToManyPost"), + ModelIndex( + fields: const ["cpkManyToManyTagID", "cpkManyToManyTaglabel"], + name: "byCpkManyToManyTag") + ]; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkPostTags.CPKMANYTOMANYPOST, + isRequired: true, + targetNames: ["cpkManyToManyPostID"], + ofModelName: (CpkManyToManyPost).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: CpkPostTags.CPKMANYTOMANYTAG, + isRequired: true, + targetNames: ["cpkManyToManyTagID", "cpkManyToManyTaglabel"], + ofModelName: (CpkManyToManyTag).toString())); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'createdAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + + modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( + fieldName: 'updatedAt', + isRequired: false, + isReadOnly: true, + ofType: ModelFieldType(ModelFieldTypeEnum.dateTime))); + }); +} + +class _CpkPostTagsModelType extends ModelType { + const _CpkPostTagsModelType(); + + @override + CpkPostTags fromJson(Map jsonData) { + return CpkPostTags.fromJson(jsonData); + } +} + +/// This is an auto generated class representing the model identifier +/// of [CpkPostTags] in your schema. +@immutable +class CpkPostTagsModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of CpkPostTagsModelIdentifier using [id] the primary key. + const CpkPostTagsModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'CpkPostTagsModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is CpkPostTagsModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/CustomTypeWithAppsyncScalarTypes.dart b/packages/amplify_datastore/example/lib/models/CustomTypeWithAppsyncScalarTypes.dart index 38c44eb85e..559a409f75 100644 --- a/packages/amplify_datastore/example/lib/models/CustomTypeWithAppsyncScalarTypes.dart +++ b/packages/amplify_datastore/example/lib/models/CustomTypeWithAppsyncScalarTypes.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; diff --git a/packages/amplify_datastore/example/lib/models/EnumField.dart b/packages/amplify_datastore/example/lib/models/EnumField.dart index eccdf67257..6c34a76ef5 100644 --- a/packages/amplify_datastore/example/lib/models/EnumField.dart +++ b/packages/amplify_datastore/example/lib/models/EnumField.dart @@ -17,6 +17,6 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously enum EnumField { yes, no } diff --git a/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalExplicit.dart b/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalExplicit.dart index 112a480bf8..c1d21db6a8 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalExplicit.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalExplicit.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the HasManyChildBiDirectionalExplicit type in your schema. @@ -36,9 +36,13 @@ class HasManyChildBiDirectionalExplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyChildBiDirectionalExplicitModelIdentifier get modelIdentifier { + return HasManyChildBiDirectionalExplicitModelIdentifier(id: id); } String? get name { @@ -111,11 +115,9 @@ class HasManyChildBiDirectionalExplicit extends Model { } HasManyChildBiDirectionalExplicit copyWith( - {String? id, - String? name, - HasManyParentBiDirectionalExplicit? hasManyParent}) { + {String? name, HasManyParentBiDirectionalExplicit? hasManyParent}) { return HasManyChildBiDirectionalExplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, hasManyParent: hasManyParent ?? this.hasManyParent); } @@ -143,8 +145,10 @@ class HasManyChildBiDirectionalExplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "hasManyChildBiDirectionalExplicit.id"); + static final QueryModelIdentifier< + HasManyChildBiDirectionalExplicitModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField HASMANYPARENT = QueryField( fieldName: "hasManyParent", @@ -155,6 +159,11 @@ class HasManyChildBiDirectionalExplicit extends Model { modelSchemaDefinition.name = "HasManyChildBiDirectionalExplicit"; modelSchemaDefinition.pluralName = "HasManyChildBiDirectionalExplicits"; + modelSchemaDefinition.indexes = [ + ModelIndex( + fields: const ["hasManyParentId", "name"], name: "byHasManyParent") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -165,7 +174,7 @@ class HasManyChildBiDirectionalExplicit extends Model { modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: HasManyChildBiDirectionalExplicit.HASMANYPARENT, isRequired: false, - targetName: "hasManyParentId", + targetNames: ["hasManyParentId"], ofModelName: (HasManyParentBiDirectionalExplicit).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( @@ -191,3 +200,43 @@ class _HasManyChildBiDirectionalExplicitModelType return HasManyChildBiDirectionalExplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyChildBiDirectionalExplicit] in your schema. +@immutable +class HasManyChildBiDirectionalExplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyChildBiDirectionalExplicitModelIdentifier using [id] the primary key. + const HasManyChildBiDirectionalExplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'HasManyChildBiDirectionalExplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyChildBiDirectionalExplicitModelIdentifier && + id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalImplicit.dart b/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalImplicit.dart index 6a583bf01d..eb417a2527 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalImplicit.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyChildBiDirectionalImplicit.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the HasManyChildBiDirectionalImplicit type in your schema. @@ -36,9 +36,13 @@ class HasManyChildBiDirectionalImplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyChildBiDirectionalImplicitModelIdentifier get modelIdentifier { + return HasManyChildBiDirectionalImplicitModelIdentifier(id: id); } String? get name { @@ -111,11 +115,9 @@ class HasManyChildBiDirectionalImplicit extends Model { } HasManyChildBiDirectionalImplicit copyWith( - {String? id, - String? name, - HasManyParentBiDirectionalImplicit? hasManyParent}) { + {String? name, HasManyParentBiDirectionalImplicit? hasManyParent}) { return HasManyChildBiDirectionalImplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, hasManyParent: hasManyParent ?? this.hasManyParent); } @@ -143,8 +145,10 @@ class HasManyChildBiDirectionalImplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "hasManyChildBiDirectionalImplicit.id"); + static final QueryModelIdentifier< + HasManyChildBiDirectionalImplicitModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField HASMANYPARENT = QueryField( fieldName: "hasManyParent", @@ -165,8 +169,9 @@ class HasManyChildBiDirectionalImplicit extends Model { modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: HasManyChildBiDirectionalImplicit.HASMANYPARENT, isRequired: false, - targetName: - "hasManyParentBiDirectionalImplicitBiDirectionalImplicitChildrenId", + targetNames: [ + "hasManyParentBiDirectionalImplicitBiDirectionalImplicitChildrenId" + ], ofModelName: (HasManyParentBiDirectionalImplicit).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( @@ -192,3 +197,43 @@ class _HasManyChildBiDirectionalImplicitModelType return HasManyChildBiDirectionalImplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyChildBiDirectionalImplicit] in your schema. +@immutable +class HasManyChildBiDirectionalImplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyChildBiDirectionalImplicitModelIdentifier using [id] the primary key. + const HasManyChildBiDirectionalImplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'HasManyChildBiDirectionalImplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyChildBiDirectionalImplicitModelIdentifier && + id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasManyChildExplicit.dart b/packages/amplify_datastore/example/lib/models/HasManyChildExplicit.dart index 8de8bc2261..12113f33aa 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyChildExplicit.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyChildExplicit.dart @@ -17,9 +17,9 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the HasManyChildExplicit type in your schema. @@ -35,9 +35,13 @@ class HasManyChildExplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyChildExplicitModelIdentifier get modelIdentifier { + return HasManyChildExplicitModelIdentifier(id: id); } String? get name { @@ -48,10 +52,10 @@ class HasManyChildExplicit extends Model { try { return _hasManyParentID!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -114,10 +118,9 @@ class HasManyChildExplicit extends Model { return buffer.toString(); } - HasManyChildExplicit copyWith( - {String? id, String? name, String? hasManyParentID}) { + HasManyChildExplicit copyWith({String? name, String? hasManyParentID}) { return HasManyChildExplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, hasManyParentID: hasManyParentID ?? this.hasManyParentID); } @@ -141,7 +144,10 @@ class HasManyChildExplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "hasManyChildExplicit.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField HASMANYPARENTID = QueryField(fieldName: "hasManyParentID"); @@ -150,6 +156,11 @@ class HasManyChildExplicit extends Model { modelSchemaDefinition.name = "HasManyChildExplicit"; modelSchemaDefinition.pluralName = "HasManyChildExplicits"; + modelSchemaDefinition.indexes = [ + ModelIndex( + fields: const ["hasManyParentID", "name"], name: "byHasManyParent") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -184,3 +195,41 @@ class _HasManyChildExplicitModelType extends ModelType { return HasManyChildExplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyChildExplicit] in your schema. +@immutable +class HasManyChildExplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyChildExplicitModelIdentifier using [id] the primary key. + const HasManyChildExplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'HasManyChildExplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyChildExplicitModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasManyChildImplicit.dart b/packages/amplify_datastore/example/lib/models/HasManyChildImplicit.dart index 23604668d2..95a6641499 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyChildImplicit.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyChildImplicit.dart @@ -17,9 +17,9 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the HasManyChildImplicit type in your schema. @@ -35,9 +35,13 @@ class HasManyChildImplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyChildImplicitModelIdentifier get modelIdentifier { + return HasManyChildImplicitModelIdentifier(id: id); } String? get name { @@ -113,9 +117,9 @@ class HasManyChildImplicit extends Model { } HasManyChildImplicit copyWith( - {String? id, String? name, String? hasManyParentImplicitChildrenId}) { + {String? name, String? hasManyParentImplicitChildrenId}) { return HasManyChildImplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, hasManyParentImplicitChildrenId: hasManyParentImplicitChildrenId ?? this.hasManyParentImplicitChildrenId); @@ -141,7 +145,10 @@ class HasManyChildImplicit extends Model { 'hasManyParentImplicitChildrenId': _hasManyParentImplicitChildrenId }; - static final QueryField ID = QueryField(fieldName: "hasManyChildImplicit.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField HASMANYPARENTIMPLICITCHILDRENID = QueryField(fieldName: "hasManyParentImplicitChildrenId"); @@ -184,3 +191,41 @@ class _HasManyChildImplicitModelType extends ModelType { return HasManyChildImplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyChildImplicit] in your schema. +@immutable +class HasManyChildImplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyChildImplicitModelIdentifier using [id] the primary key. + const HasManyChildImplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'HasManyChildImplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyChildImplicitModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasManyParent.dart b/packages/amplify_datastore/example/lib/models/HasManyParent.dart index abcc3394eb..731d44c05b 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyParent.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyParent.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -38,9 +38,13 @@ class HasManyParent extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyParentModelIdentifier get modelIdentifier { + return HasManyParentModelIdentifier(id: id); } String? get name { @@ -129,12 +133,11 @@ class HasManyParent extends Model { } HasManyParent copyWith( - {String? id, - String? name, + {String? name, List? implicitChildren, List? explicitChildren}) { return HasManyParent._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, implicitChildren: implicitChildren ?? this.implicitChildren, explicitChildren: explicitChildren ?? this.explicitChildren); @@ -177,7 +180,9 @@ class HasManyParent extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "hasManyParent.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField IMPLICITCHILDREN = QueryField( fieldName: "implicitChildren", @@ -233,3 +238,40 @@ class _HasManyParentModelType extends ModelType { return HasManyParent.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyParent] in your schema. +@immutable +class HasManyParentModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyParentModelIdentifier using [id] the primary key. + const HasManyParentModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'HasManyParentModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyParentModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalExplicit.dart b/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalExplicit.dart index 504f1687b0..dfd5356d58 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalExplicit.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalExplicit.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,9 +37,13 @@ class HasManyParentBiDirectionalExplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyParentBiDirectionalExplicitModelIdentifier get modelIdentifier { + return HasManyParentBiDirectionalExplicitModelIdentifier(id: id); } String? get name { @@ -117,11 +121,10 @@ class HasManyParentBiDirectionalExplicit extends Model { } HasManyParentBiDirectionalExplicit copyWith( - {String? id, - String? name, + {String? name, List? biDirectionalExplicitChildren}) { return HasManyParentBiDirectionalExplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, biDirectionalExplicitChildren: biDirectionalExplicitChildren ?? this.biDirectionalExplicitChildren); @@ -155,8 +158,10 @@ class HasManyParentBiDirectionalExplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "hasManyParentBiDirectionalExplicit.id"); + static final QueryModelIdentifier< + HasManyParentBiDirectionalExplicitModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField BIDIRECTIONALEXPLICITCHILDREN = QueryField( fieldName: "biDirectionalExplicitChildren", @@ -203,3 +208,43 @@ class _HasManyParentBiDirectionalExplicitModelType return HasManyParentBiDirectionalExplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyParentBiDirectionalExplicit] in your schema. +@immutable +class HasManyParentBiDirectionalExplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyParentBiDirectionalExplicitModelIdentifier using [id] the primary key. + const HasManyParentBiDirectionalExplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'HasManyParentBiDirectionalExplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyParentBiDirectionalExplicitModelIdentifier && + id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalImplicit.dart b/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalImplicit.dart index 259d460371..0a7d6a0782 100644 --- a/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalImplicit.dart +++ b/packages/amplify_datastore/example/lib/models/HasManyParentBiDirectionalImplicit.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,9 +37,13 @@ class HasManyParentBiDirectionalImplicit extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasManyParentBiDirectionalImplicitModelIdentifier get modelIdentifier { + return HasManyParentBiDirectionalImplicitModelIdentifier(id: id); } String? get name { @@ -117,11 +121,10 @@ class HasManyParentBiDirectionalImplicit extends Model { } HasManyParentBiDirectionalImplicit copyWith( - {String? id, - String? name, + {String? name, List? biDirectionalImplicitChildren}) { return HasManyParentBiDirectionalImplicit._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, biDirectionalImplicitChildren: biDirectionalImplicitChildren ?? this.biDirectionalImplicitChildren); @@ -155,8 +158,10 @@ class HasManyParentBiDirectionalImplicit extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "hasManyParentBiDirectionalImplicit.id"); + static final QueryModelIdentifier< + HasManyParentBiDirectionalImplicitModelIdentifier> MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField BIDIRECTIONALIMPLICITCHILDREN = QueryField( fieldName: "biDirectionalImplicitChildren", @@ -203,3 +208,43 @@ class _HasManyParentBiDirectionalImplicitModelType return HasManyParentBiDirectionalImplicit.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasManyParentBiDirectionalImplicit] in your schema. +@immutable +class HasManyParentBiDirectionalImplicitModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of HasManyParentBiDirectionalImplicitModelIdentifier using [id] the primary key. + const HasManyParentBiDirectionalImplicitModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => + 'HasManyParentBiDirectionalImplicitModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasManyParentBiDirectionalImplicitModelIdentifier && + id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasOneChild.dart b/packages/amplify_datastore/example/lib/models/HasOneChild.dart index 3fced6064f..2c0154ab26 100644 --- a/packages/amplify_datastore/example/lib/models/HasOneChild.dart +++ b/packages/amplify_datastore/example/lib/models/HasOneChild.dart @@ -17,9 +17,9 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the HasOneChild type in your schema. @@ -34,9 +34,13 @@ class HasOneChild extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasOneChildModelIdentifier get modelIdentifier { + return HasOneChildModelIdentifier(id: id); } String? get name { @@ -91,8 +95,8 @@ class HasOneChild extends Model { return buffer.toString(); } - HasOneChild copyWith({String? id, String? name}) { - return HasOneChild._internal(id: id ?? this.id, name: name ?? this.name); + HasOneChild copyWith({String? name}) { + return HasOneChild._internal(id: id, name: name ?? this.name); } HasOneChild.fromJson(Map json) @@ -112,7 +116,9 @@ class HasOneChild extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "hasOneChild.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { @@ -148,3 +154,40 @@ class _HasOneChildModelType extends ModelType { return HasOneChild.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasOneChild] in your schema. +@immutable +class HasOneChildModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of HasOneChildModelIdentifier using [id] the primary key. + const HasOneChildModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'HasOneChildModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasOneChildModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/HasOneParent.dart b/packages/amplify_datastore/example/lib/models/HasOneParent.dart index ecdf4bca17..af3e650339 100644 --- a/packages/amplify_datastore/example/lib/models/HasOneParent.dart +++ b/packages/amplify_datastore/example/lib/models/HasOneParent.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the HasOneParent type in your schema. @@ -39,9 +39,13 @@ class HasOneParent extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + HasOneParentModelIdentifier get modelIdentifier { + return HasOneParentModelIdentifier(id: id); } String? get name { @@ -146,14 +150,13 @@ class HasOneParent extends Model { } HasOneParent copyWith( - {String? id, - String? name, + {String? name, HasOneChild? implicitChild, String? explicitChildID, HasOneChild? explicitChild, String? hasOneParentImplicitChildId}) { return HasOneParent._internal( - id: id ?? this.id, + id: id, name: name ?? this.name, implicitChild: implicitChild ?? this.implicitChild, explicitChildID: explicitChildID ?? this.explicitChildID, @@ -193,7 +196,9 @@ class HasOneParent extends Model { 'hasOneParentImplicitChildId': _hasOneParentImplicitChildId }; - static final QueryField ID = QueryField(fieldName: "hasOneParent.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField NAME = QueryField(fieldName: "name"); static final QueryField IMPLICITCHILD = QueryField( fieldName: "implicitChild", @@ -263,3 +268,40 @@ class _HasOneParentModelType extends ModelType { return HasOneParent.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [HasOneParent] in your schema. +@immutable +class HasOneParentModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of HasOneParentModelIdentifier using [id] the primary key. + const HasOneParentModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'HasOneParentModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is HasOneParentModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/ModelProvider.dart b/packages/amplify_datastore/example/lib/models/ModelProvider.dart index c677a5e4ab..f40857464b 100644 --- a/packages/amplify_datastore/example/lib/models/ModelProvider.dart +++ b/packages/amplify_datastore/example/lib/models/ModelProvider.dart @@ -17,14 +17,33 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'BelongsToChildExplicit.dart'; import 'BelongsToChildImplicit.dart'; import 'BelongsToParent.dart'; import 'Blog.dart'; import 'Comment.dart'; +import 'CpkHasManyChildBidirectionalExplicit.dart'; +import 'CpkHasManyChildBidirectionalImplicit.dart'; +import 'CpkHasManyParentBidirectionalExplicit.dart'; +import 'CpkHasManyParentBidirectionalImplicit.dart'; +import 'CpkHasManyUnidirectionalChildExplicit.dart'; +import 'CpkHasManyUnidirectionalChildImplicit.dart'; +import 'CpkHasManyUnidirectionalParent.dart'; +import 'CpkHasOneUnidirectionalChild.dart'; +import 'CpkHasOneUnidirectionalParent.dart'; +import 'CpkInventory.dart'; +import 'CpkManyToManyPost.dart'; +import 'CpkManyToManyTag.dart'; +import 'CpkOneToOneBidirectionalChildExplicitCD.dart'; +import 'CpkOneToOneBidirectionalChildExplicitID.dart'; +import 'CpkOneToOneBidirectionalChildImplicitCD.dart'; +import 'CpkOneToOneBidirectionalChildImplicitID.dart'; +import 'CpkOneToOneBidirectionalParentCD.dart'; +import 'CpkOneToOneBidirectionalParentID.dart'; +import 'CpkPostTags.dart'; import 'HasManyChildBiDirectionalExplicit.dart'; import 'HasManyChildBiDirectionalImplicit.dart'; import 'HasManyChildExplicit.dart'; @@ -51,6 +70,25 @@ export 'BelongsToChildImplicit.dart'; export 'BelongsToParent.dart'; export 'Blog.dart'; export 'Comment.dart'; +export 'CpkHasManyChildBidirectionalExplicit.dart'; +export 'CpkHasManyChildBidirectionalImplicit.dart'; +export 'CpkHasManyParentBidirectionalExplicit.dart'; +export 'CpkHasManyParentBidirectionalImplicit.dart'; +export 'CpkHasManyUnidirectionalChildExplicit.dart'; +export 'CpkHasManyUnidirectionalChildImplicit.dart'; +export 'CpkHasManyUnidirectionalParent.dart'; +export 'CpkHasOneUnidirectionalChild.dart'; +export 'CpkHasOneUnidirectionalParent.dart'; +export 'CpkInventory.dart'; +export 'CpkManyToManyPost.dart'; +export 'CpkManyToManyTag.dart'; +export 'CpkOneToOneBidirectionalChildExplicitCD.dart'; +export 'CpkOneToOneBidirectionalChildExplicitID.dart'; +export 'CpkOneToOneBidirectionalChildImplicitCD.dart'; +export 'CpkOneToOneBidirectionalChildImplicitID.dart'; +export 'CpkOneToOneBidirectionalParentCD.dart'; +export 'CpkOneToOneBidirectionalParentID.dart'; +export 'CpkPostTags.dart'; export 'CustomTypeWithAppsyncScalarTypes.dart'; export 'EnumField.dart'; export 'HasManyChildBiDirectionalExplicit.dart'; @@ -75,29 +113,50 @@ export 'Tag.dart'; class ModelProvider implements ModelProviderInterface { @override - String version = "f80fece878bf91a76f44577fe599b120"; + String version = "5bb609b6f4dc361bb6c2aaa3e1ee7560"; @override List modelSchemas = [ - BelongsToChildExplicit.schema, - BelongsToChildImplicit.schema, - BelongsToParent.schema, + // the schemas that are commented out are not needed to run + // the example App + // BelongsToChildExplicit.schema, + // BelongsToChildImplicit.schema, + // BelongsToParent.schema, Blog.schema, Comment.schema, - HasManyChildBiDirectionalExplicit.schema, - HasManyChildBiDirectionalImplicit.schema, - HasManyChildExplicit.schema, - HasManyChildImplicit.schema, - HasManyParent.schema, - HasManyParentBiDirectionalExplicit.schema, - HasManyParentBiDirectionalImplicit.schema, - HasOneChild.schema, - HasOneParent.schema, + // CpkHasManyChildBidirectionalExplicit.schema, + // CpkHasManyChildBidirectionalImplicit.schema, + // CpkHasManyParentBidirectionalExplicit.schema, + // CpkHasManyParentBidirectionalImplicit.schema, + // CpkHasManyUnidirectionalChildExplicit.schema, + // CpkHasManyUnidirectionalChildImplicit.schema, + // CpkHasManyUnidirectionalParent.schema, + // CpkHasOneUnidirectionalChild.schema, + // CpkHasOneUnidirectionalParent.schema, + // CpkInventory.schema, + // CpkManyToManyPost.schema, + // CpkManyToManyTag.schema, + // CpkOneToOneBidirectionalChildExplicitCD.schema, + // CpkOneToOneBidirectionalChildExplicitID.schema, + // CpkOneToOneBidirectionalChildImplicitCD.schema, + // CpkOneToOneBidirectionalChildImplicitID.schema, + // CpkOneToOneBidirectionalParentCD.schema, + // CpkOneToOneBidirectionalParentID.schema, + // CpkPostTags.schema, + // HasManyChildBiDirectionalExplicit.schema, + // HasManyChildBiDirectionalImplicit.schema, + // HasManyChildExplicit.schema, + // HasManyChildImplicit.schema, + // HasManyParent.schema, + // HasManyParentBiDirectionalExplicit.schema, + // HasManyParentBiDirectionalImplicit.schema, + // HasOneChild.schema, + // HasOneParent.schema, ModelWithAppsyncScalarTypes.schema, ModelWithCustomType.schema, ModelWithEnum.schema, - MultiRelatedAttendee.schema, - MultiRelatedMeeting.schema, - MultiRelatedRegistration.schema, + // MultiRelatedAttendee.schema, + // MultiRelatedMeeting.schema, + // MultiRelatedRegistration.schema, Post.schema, PostTags.schema, Tag.schema @@ -123,6 +182,44 @@ class ModelProvider implements ModelProviderInterface { return Blog.classType; case "Comment": return Comment.classType; + case "CpkHasManyChildBidirectionalExplicit": + return CpkHasManyChildBidirectionalExplicit.classType; + case "CpkHasManyChildBidirectionalImplicit": + return CpkHasManyChildBidirectionalImplicit.classType; + case "CpkHasManyParentBidirectionalExplicit": + return CpkHasManyParentBidirectionalExplicit.classType; + case "CpkHasManyParentBidirectionalImplicit": + return CpkHasManyParentBidirectionalImplicit.classType; + case "CpkHasManyUnidirectionalChildExplicit": + return CpkHasManyUnidirectionalChildExplicit.classType; + case "CpkHasManyUnidirectionalChildImplicit": + return CpkHasManyUnidirectionalChildImplicit.classType; + case "CpkHasManyUnidirectionalParent": + return CpkHasManyUnidirectionalParent.classType; + case "CpkHasOneUnidirectionalChild": + return CpkHasOneUnidirectionalChild.classType; + case "CpkHasOneUnidirectionalParent": + return CpkHasOneUnidirectionalParent.classType; + case "CpkInventory": + return CpkInventory.classType; + case "CpkManyToManyPost": + return CpkManyToManyPost.classType; + case "CpkManyToManyTag": + return CpkManyToManyTag.classType; + case "CpkOneToOneBidirectionalChildExplicitCD": + return CpkOneToOneBidirectionalChildExplicitCD.classType; + case "CpkOneToOneBidirectionalChildExplicitID": + return CpkOneToOneBidirectionalChildExplicitID.classType; + case "CpkOneToOneBidirectionalChildImplicitCD": + return CpkOneToOneBidirectionalChildImplicitCD.classType; + case "CpkOneToOneBidirectionalChildImplicitID": + return CpkOneToOneBidirectionalChildImplicitID.classType; + case "CpkOneToOneBidirectionalParentCD": + return CpkOneToOneBidirectionalParentCD.classType; + case "CpkOneToOneBidirectionalParentID": + return CpkOneToOneBidirectionalParentID.classType; + case "CpkPostTags": + return CpkPostTags.classType; case "HasManyChildBiDirectionalExplicit": return HasManyChildBiDirectionalExplicit.classType; case "HasManyChildBiDirectionalImplicit": diff --git a/packages/amplify_datastore/example/lib/models/ModelWithAppsyncScalarTypes.dart b/packages/amplify_datastore/example/lib/models/ModelWithAppsyncScalarTypes.dart index 0176d75e54..cf1eff1866 100644 --- a/packages/amplify_datastore/example/lib/models/ModelWithAppsyncScalarTypes.dart +++ b/packages/amplify_datastore/example/lib/models/ModelWithAppsyncScalarTypes.dart @@ -17,9 +17,9 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -62,9 +62,13 @@ class ModelWithAppsyncScalarTypes extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + ModelWithAppsyncScalarTypesModelIdentifier get modelIdentifier { + return ModelWithAppsyncScalarTypesModelIdentifier(id: id); } String? get stringValue { @@ -498,8 +502,7 @@ class ModelWithAppsyncScalarTypes extends Model { } ModelWithAppsyncScalarTypes copyWith( - {String? id, - String? stringValue, + {String? stringValue, String? altStringValue, List? listOfStringValue, int? intValue, @@ -528,7 +531,7 @@ class ModelWithAppsyncScalarTypes extends Model { String? awsIPAddressValue, List? listOfAWSIPAddressValue}) { return ModelWithAppsyncScalarTypes._internal( - id: id ?? this.id, + id: id, stringValue: stringValue ?? this.stringValue, altStringValue: altStringValue ?? this.altStringValue, listOfStringValue: listOfStringValue ?? this.listOfStringValue, @@ -658,8 +661,10 @@ class ModelWithAppsyncScalarTypes extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "modelWithAppsyncScalarTypes.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField STRINGVALUE = QueryField(fieldName: "stringValue"); static final QueryField ALTSTRINGVALUE = QueryField(fieldName: "altStringValue"); @@ -903,3 +908,42 @@ class _ModelWithAppsyncScalarTypesModelType return ModelWithAppsyncScalarTypes.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [ModelWithAppsyncScalarTypes] in your schema. +@immutable +class ModelWithAppsyncScalarTypesModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of ModelWithAppsyncScalarTypesModelIdentifier using [id] the primary key. + const ModelWithAppsyncScalarTypesModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'ModelWithAppsyncScalarTypesModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is ModelWithAppsyncScalarTypesModelIdentifier && + id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/ModelWithCustomType.dart b/packages/amplify_datastore/example/lib/models/ModelWithCustomType.dart index a99e690e30..32c2d630bb 100644 --- a/packages/amplify_datastore/example/lib/models/ModelWithCustomType.dart +++ b/packages/amplify_datastore/example/lib/models/ModelWithCustomType.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,9 +37,13 @@ class ModelWithCustomType extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + ModelWithCustomTypeModelIdentifier get modelIdentifier { + return ModelWithCustomTypeModelIdentifier(id: id); } CustomTypeWithAppsyncScalarTypes? get customTypeValue { @@ -124,11 +128,10 @@ class ModelWithCustomType extends Model { } ModelWithCustomType copyWith( - {String? id, - CustomTypeWithAppsyncScalarTypes? customTypeValue, + {CustomTypeWithAppsyncScalarTypes? customTypeValue, List? listOfCustomTypeValue}) { return ModelWithCustomType._internal( - id: id ?? this.id, + id: id, customTypeValue: customTypeValue ?? this.customTypeValue, listOfCustomTypeValue: listOfCustomTypeValue ?? this.listOfCustomTypeValue); @@ -165,7 +168,10 @@ class ModelWithCustomType extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "modelWithCustomType.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField CUSTOMTYPEVALUE = QueryField(fieldName: "customTypeValue"); static final QueryField LISTOFCUSTOMTYPEVALUE = @@ -212,3 +218,41 @@ class _ModelWithCustomTypeModelType extends ModelType { return ModelWithCustomType.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [ModelWithCustomType] in your schema. +@immutable +class ModelWithCustomTypeModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of ModelWithCustomTypeModelIdentifier using [id] the primary key. + const ModelWithCustomTypeModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'ModelWithCustomTypeModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is ModelWithCustomTypeModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/ModelWithEnum.dart b/packages/amplify_datastore/example/lib/models/ModelWithEnum.dart index 7e2d5676f6..f1a035677a 100644 --- a/packages/amplify_datastore/example/lib/models/ModelWithEnum.dart +++ b/packages/amplify_datastore/example/lib/models/ModelWithEnum.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,9 +37,13 @@ class ModelWithEnum extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + ModelWithEnumModelIdentifier get modelIdentifier { + return ModelWithEnumModelIdentifier(id: id); } EnumField? get enumField { @@ -117,9 +121,9 @@ class ModelWithEnum extends Model { } ModelWithEnum copyWith( - {String? id, EnumField? enumField, List? listOfEnumField}) { + {EnumField? enumField, List? listOfEnumField}) { return ModelWithEnum._internal( - id: id ?? this.id, + id: id, enumField: enumField ?? this.enumField, listOfEnumField: listOfEnumField ?? this.listOfEnumField); } @@ -149,7 +153,9 @@ class ModelWithEnum extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "modelWithEnum.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField ENUMFIELD = QueryField(fieldName: "enumField"); static final QueryField LISTOFENUMFIELD = QueryField(fieldName: "listOfEnumField"); @@ -194,3 +200,40 @@ class _ModelWithEnumModelType extends ModelType { return ModelWithEnum.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [ModelWithEnum] in your schema. +@immutable +class ModelWithEnumModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of ModelWithEnumModelIdentifier using [id] the primary key. + const ModelWithEnumModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'ModelWithEnumModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is ModelWithEnumModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/MultiRelatedAttendee.dart b/packages/amplify_datastore/example/lib/models/MultiRelatedAttendee.dart index edb832aa45..b0930d7200 100644 --- a/packages/amplify_datastore/example/lib/models/MultiRelatedAttendee.dart +++ b/packages/amplify_datastore/example/lib/models/MultiRelatedAttendee.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -36,9 +36,13 @@ class MultiRelatedAttendee extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + MultiRelatedAttendeeModelIdentifier get modelIdentifier { + return MultiRelatedAttendeeModelIdentifier(id: id); } List? get meetings { @@ -99,10 +103,9 @@ class MultiRelatedAttendee extends Model { return buffer.toString(); } - MultiRelatedAttendee copyWith( - {String? id, List? meetings}) { + MultiRelatedAttendee copyWith({List? meetings}) { return MultiRelatedAttendee._internal( - id: id ?? this.id, meetings: meetings ?? this.meetings); + id: id, meetings: meetings ?? this.meetings); } MultiRelatedAttendee.fromJson(Map json) @@ -130,7 +133,10 @@ class MultiRelatedAttendee extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "multiRelatedAttendee.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField MEETINGS = QueryField( fieldName: "meetings", fieldType: ModelFieldType(ModelFieldTypeEnum.model, @@ -140,6 +146,10 @@ class MultiRelatedAttendee extends Model { modelSchemaDefinition.name = "MultiRelatedAttendee"; modelSchemaDefinition.pluralName = "MultiRelatedAttendees"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id"], name: null) + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( @@ -170,3 +180,41 @@ class _MultiRelatedAttendeeModelType extends ModelType { return MultiRelatedAttendee.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [MultiRelatedAttendee] in your schema. +@immutable +class MultiRelatedAttendeeModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of MultiRelatedAttendeeModelIdentifier using [id] the primary key. + const MultiRelatedAttendeeModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'MultiRelatedAttendeeModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is MultiRelatedAttendeeModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/MultiRelatedMeeting.dart b/packages/amplify_datastore/example/lib/models/MultiRelatedMeeting.dart index 96ad6b1355..a8f25f5780 100644 --- a/packages/amplify_datastore/example/lib/models/MultiRelatedMeeting.dart +++ b/packages/amplify_datastore/example/lib/models/MultiRelatedMeeting.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,19 +37,23 @@ class MultiRelatedMeeting extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + MultiRelatedMeetingModelIdentifier get modelIdentifier { + return MultiRelatedMeetingModelIdentifier(id: id); } String get title { try { return _title!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -120,9 +124,9 @@ class MultiRelatedMeeting extends Model { } MultiRelatedMeeting copyWith( - {String? id, String? title, List? attendees}) { + {String? title, List? attendees}) { return MultiRelatedMeeting._internal( - id: id ?? this.id, + id: id, title: title ?? this.title, attendees: attendees ?? this.attendees); } @@ -154,7 +158,10 @@ class MultiRelatedMeeting extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "multiRelatedMeeting.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField TITLE = QueryField(fieldName: "title"); static final QueryField ATTENDEES = QueryField( fieldName: "attendees", @@ -165,6 +172,10 @@ class MultiRelatedMeeting extends Model { modelSchemaDefinition.name = "MultiRelatedMeeting"; modelSchemaDefinition.pluralName = "MultiRelatedMeetings"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id"], name: null) + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -200,3 +211,41 @@ class _MultiRelatedMeetingModelType extends ModelType { return MultiRelatedMeeting.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [MultiRelatedMeeting] in your schema. +@immutable +class MultiRelatedMeetingModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of MultiRelatedMeetingModelIdentifier using [id] the primary key. + const MultiRelatedMeetingModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'MultiRelatedMeetingModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is MultiRelatedMeetingModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/MultiRelatedRegistration.dart b/packages/amplify_datastore/example/lib/models/MultiRelatedRegistration.dart index 96404606ad..9e85d043e1 100644 --- a/packages/amplify_datastore/example/lib/models/MultiRelatedRegistration.dart +++ b/packages/amplify_datastore/example/lib/models/MultiRelatedRegistration.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the MultiRelatedRegistration type in your schema. @@ -36,19 +36,23 @@ class MultiRelatedRegistration extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + MultiRelatedRegistrationModelIdentifier get modelIdentifier { + return MultiRelatedRegistrationModelIdentifier(id: id); } MultiRelatedMeeting get meeting { try { return _meeting!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -58,10 +62,10 @@ class MultiRelatedRegistration extends Model { try { return _attendee!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -134,11 +138,9 @@ class MultiRelatedRegistration extends Model { } MultiRelatedRegistration copyWith( - {String? id, - MultiRelatedMeeting? meeting, - MultiRelatedAttendee? attendee}) { + {MultiRelatedMeeting? meeting, MultiRelatedAttendee? attendee}) { return MultiRelatedRegistration._internal( - id: id ?? this.id, + id: id, meeting: meeting ?? this.meeting, attendee: attendee ?? this.attendee); } @@ -168,8 +170,10 @@ class MultiRelatedRegistration extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = - QueryField(fieldName: "multiRelatedRegistration.id"); + static final QueryModelIdentifier + MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField MEETING = QueryField( fieldName: "meeting", fieldType: ModelFieldType(ModelFieldTypeEnum.model, @@ -183,18 +187,24 @@ class MultiRelatedRegistration extends Model { modelSchemaDefinition.name = "MultiRelatedRegistration"; modelSchemaDefinition.pluralName = "MultiRelatedRegistrations"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["id"], name: null), + ModelIndex(fields: const ["meetingId", "attendeeId"], name: "byMeeting"), + ModelIndex(fields: const ["attendeeId", "meetingId"], name: "byAttendee") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: MultiRelatedRegistration.MEETING, isRequired: true, - targetName: "meetingId", + targetNames: ["meetingId"], ofModelName: (MultiRelatedMeeting).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: MultiRelatedRegistration.ATTENDEE, isRequired: true, - targetName: "attendeeId", + targetNames: ["attendeeId"], ofModelName: (MultiRelatedAttendee).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( @@ -220,3 +230,41 @@ class _MultiRelatedRegistrationModelType return MultiRelatedRegistration.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [MultiRelatedRegistration] in your schema. +@immutable +class MultiRelatedRegistrationModelIdentifier + implements ModelIdentifier { + final String id; + + /// Create an instance of MultiRelatedRegistrationModelIdentifier using [id] the primary key. + const MultiRelatedRegistrationModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'MultiRelatedRegistrationModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is MultiRelatedRegistrationModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/Post.dart b/packages/amplify_datastore/example/lib/models/Post.dart index fc3056a193..2c4f91fa9d 100644 --- a/packages/amplify_datastore/example/lib/models/Post.dart +++ b/packages/amplify_datastore/example/lib/models/Post.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -41,19 +41,23 @@ class Post extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + PostModelIdentifier get modelIdentifier { + return PostModelIdentifier(id: id); } String get title { try { return _title!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -63,10 +67,10 @@ class Post extends Model { try { return _rating!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -177,15 +181,14 @@ class Post extends Model { } Post copyWith( - {String? id, - String? title, + {String? title, int? rating, TemporalDateTime? created, Blog? blog, List? comments, List? tags}) { return Post._internal( - id: id ?? this.id, + id: id, title: title ?? this.title, rating: rating ?? this.rating, created: created ?? this.created, @@ -238,7 +241,9 @@ class Post extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "post.id"); + static final QueryModelIdentifier MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField TITLE = QueryField(fieldName: "title"); static final QueryField RATING = QueryField(fieldName: "rating"); static final QueryField CREATED = QueryField(fieldName: "created"); @@ -259,6 +264,10 @@ class Post extends Model { modelSchemaDefinition.name = "Post"; modelSchemaDefinition.pluralName = "Posts"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["blogID"], name: "byBlog") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.field( @@ -279,7 +288,7 @@ class Post extends Model { modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: Post.BLOG, isRequired: false, - targetName: "blogID", + targetNames: ["blogID"], ofModelName: (Blog).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( @@ -316,3 +325,40 @@ class _PostModelType extends ModelType { return Post.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Post] in your schema. +@immutable +class PostModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of PostModelIdentifier using [id] the primary key. + const PostModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'PostModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is PostModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/PostTags.dart b/packages/amplify_datastore/example/lib/models/PostTags.dart index 1a55812c5f..4b05576d7c 100644 --- a/packages/amplify_datastore/example/lib/models/PostTags.dart +++ b/packages/amplify_datastore/example/lib/models/PostTags.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the PostTags type in your schema. @@ -36,19 +36,23 @@ class PostTags extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + PostTagsModelIdentifier get modelIdentifier { + return PostTagsModelIdentifier(id: id); } Post get post { try { return _post!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -58,10 +62,10 @@ class PostTags extends Model { try { return _tag!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -121,9 +125,9 @@ class PostTags extends Model { return buffer.toString(); } - PostTags copyWith({String? id, Post? post, Tag? tag}) { + PostTags copyWith({Post? post, Tag? tag}) { return PostTags._internal( - id: id ?? this.id, post: post ?? this.post, tag: tag ?? this.tag); + id: id, post: post ?? this.post, tag: tag ?? this.tag); } PostTags.fromJson(Map json) @@ -151,7 +155,9 @@ class PostTags extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "postTags.id"); + static final QueryModelIdentifier MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField POST = QueryField( fieldName: "post", fieldType: ModelFieldType(ModelFieldTypeEnum.model, @@ -165,18 +171,23 @@ class PostTags extends Model { modelSchemaDefinition.name = "PostTags"; modelSchemaDefinition.pluralName = "PostTags"; + modelSchemaDefinition.indexes = [ + ModelIndex(fields: const ["postID"], name: "byPost"), + ModelIndex(fields: const ["tagID"], name: "byTag") + ]; + modelSchemaDefinition.addField(ModelFieldDefinition.id()); modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: PostTags.POST, isRequired: true, - targetName: "postID", + targetNames: ["postID"], ofModelName: (Post).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( key: PostTags.TAG, isRequired: true, - targetName: "tagID", + targetNames: ["tagID"], ofModelName: (Tag).toString())); modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField( @@ -201,3 +212,40 @@ class _PostTagsModelType extends ModelType { return PostTags.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [PostTags] in your schema. +@immutable +class PostTagsModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of PostTagsModelIdentifier using [id] the primary key. + const PostTagsModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'PostTagsModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is PostTagsModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/lib/models/SimpleCustomType.dart b/packages/amplify_datastore/example/lib/models/SimpleCustomType.dart index e3b0f5d8a6..ab0cedf0b8 100644 --- a/packages/amplify_datastore/example/lib/models/SimpleCustomType.dart +++ b/packages/amplify_datastore/example/lib/models/SimpleCustomType.dart @@ -17,9 +17,9 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:flutter/foundation.dart'; /// This is an auto generated class representing the SimpleCustomType type in your schema. @@ -31,10 +31,10 @@ class SimpleCustomType { try { return _foo!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } diff --git a/packages/amplify_datastore/example/lib/models/Tag.dart b/packages/amplify_datastore/example/lib/models/Tag.dart index 305e1670af..0a019615bb 100644 --- a/packages/amplify_datastore/example/lib/models/Tag.dart +++ b/packages/amplify_datastore/example/lib/models/Tag.dart @@ -17,10 +17,10 @@ // Generated files can be excluded from analysis in analysis_options.yaml // For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis -// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code +// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously import 'ModelProvider.dart'; -import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:amplify_core/amplify_core.dart'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -37,19 +37,23 @@ class Tag extends Model { @override getInstanceType() => classType; + @Deprecated( + '[getId] is being deprecated in favor of custom primary key feature. Use getter [modelIdentifier] to get model identifier.') @override - String getId() { - return id; + String getId() => id; + + TagModelIdentifier get modelIdentifier { + return TagModelIdentifier(id: id); } String get label { try { return _label!; } catch (e) { - throw DataStoreException( - DataStoreExceptionMessages + throw AmplifyCodeGenModelException( + AmplifyExceptionMessages .codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: DataStoreExceptionMessages + recoverySuggestion: AmplifyExceptionMessages .codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString()); } @@ -114,11 +118,9 @@ class Tag extends Model { return buffer.toString(); } - Tag copyWith({String? id, String? label, List? posts}) { + Tag copyWith({String? label, List? posts}) { return Tag._internal( - id: id ?? this.id, - label: label ?? this.label, - posts: posts ?? this.posts); + id: id, label: label ?? this.label, posts: posts ?? this.posts); } Tag.fromJson(Map json) @@ -146,7 +148,9 @@ class Tag extends Model { 'updatedAt': _updatedAt?.format() }; - static final QueryField ID = QueryField(fieldName: "tag.id"); + static final QueryModelIdentifier MODEL_IDENTIFIER = + QueryModelIdentifier(); + static final QueryField ID = QueryField(fieldName: "id"); static final QueryField LABEL = QueryField(fieldName: "label"); static final QueryField POSTS = QueryField( fieldName: "posts", @@ -192,3 +196,40 @@ class _TagModelType extends ModelType { return Tag.fromJson(jsonData); } } + +/// This is an auto generated class representing the model identifier +/// of [Tag] in your schema. +@immutable +class TagModelIdentifier implements ModelIdentifier { + final String id; + + /// Create an instance of TagModelIdentifier using [id] the primary key. + const TagModelIdentifier({required this.id}); + + @override + Map serializeAsMap() => ({'id': id}); + + @override + List> serializeAsList() => serializeAsMap() + .entries + .map((entry) => ({entry.key: entry.value})) + .toList(); + + @override + String serializeAsString() => serializeAsMap().values.join('#'); + + @override + String toString() => 'TagModelIdentifier(id: $id)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + return other is TagModelIdentifier && id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/packages/amplify_datastore/example/tool/schema.graphql b/packages/amplify_datastore/example/tool/schema.graphql index ba45f73790..4aaf95b317 100644 --- a/packages/amplify_datastore/example/tool/schema.graphql +++ b/packages/amplify_datastore/example/tool/schema.graphql @@ -216,3 +216,104 @@ type MultiRelatedRegistration @model { attendeeId: ID @index(name: "byAttendee", sortKeyFields: ["meetingId"]) attendee: MultiRelatedAttendee! @belongsTo(fields: ["attendeeId"]) } + +type CPKInventory @model { + productId: ID! @primaryKey(sortKeyFields: ["productName", "warehouseId"]) + productName: String! + warehouseId: String! + description: String +} + +# type CPKHasOneParent @model { +# id: ID! @primaryKey(sortKeyFields: ["name"]) +# name: String! +# implicitChild: CPKHasOneChild @hasOne +# explicitChildId: ID +# explicitChildName: String +# explicitChild: CPKHasOneChild +# @hasOne(fields: ["explicitChildId", "explicitChildName"]) +# } + +# type CPKHasOneChild @model { +# id: ID! @primaryKey(sortKeyFields: ["name"]) +# name: String! +# } + +# type CPKBelongsToParent @model { +# id: ID! @primaryKey(sortKeyFields: ["name"]) +# name: String! +# implicitChild: CPKBelongsToChildImplicit @hasOne +# explicitChild: CPKBelongsToChildExplicit @hasOne +# } + +# type CPKBelongsToChildImplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["name"]) +# name: String! +# parent: CPKHasOneParent @belongsTo +# } + +# type CPKBelongsToChildExplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["name"]) +# name: String! +# parentId: ID! +# parentName: String! +# parent: CPKHasOneParent @belongsTo(fields: ["projectId", "projectName"]) +# } + +# type CPKHasManyParent @model { +# id: ID! @primaryKey(sortKeyFields: ["title"]) +# title: String! +# implicitChildren: [CPKHasManyChildImplicit] @hasMany +# explicitChildren: [CPKHasManyChildExplicit] +# @hasMany(indexName: "byCPKHasManyParent", fields: ["id"]) +# } + +# type CPKHasManyChildImplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["content"]) +# content: String! +# } + +# type CPKHasManyChildExplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["content"]) +# content: String! +# hasManyParentId: ID +# @index(name: "byCPKHasManyParent", sortKeyFields: ["content"]) +# } + +# type CPKHasManyParentBidirectionalImplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["title"]) +# title: String! +# cpkHasManyImplicitChildren: [CPKHasManyChildImplicit] @hasMany +# } + +# type CPKHasManyChildImplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["content"]) +# content: String! +# hasManyParent: CPKHasManyParentBidirectionalImplicit @belongsTo +# } + +# type CPKHasManyParentBidirectionalExplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["title"]) +# title: String! +# cpkHasManyExplicitChildren: [CPKHasManyChildExplicit] @hasMany +# } + +# type CPKHasManyChildExplicit @model { +# id: ID! @primaryKey(sortKeyFields: ["content"]) +# content: String! +# hasManyParentId: ID @index(name: "byCPKHasManyParentBidirectionalExplicit", sortKeyFields: ["content"]) +# hasManyParent: CPKHasManyParentBidirectionalImplicit @belongsTo(fields: ["hasManyParentID"]) +# } + +# type CPKManyToManyPost @model { +# id: ID! +# title: String! +# content: String +# tags: [CPKManyToManyTag] @manyToMany(relationName: "CPKPostTags") +# } + +# type CPKManyToManyTag @model { +# id: ID! @primaryKey(sortKeyFields: ["label"]) +# label: String! +# posts: [CPKManyToManyPost] @manyToMany(relationName: "CPKPostTags") +# } From 33b710d49b8fbfbfe0b282c44072a0d9a504c0f2 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 26 May 2022 16:08:47 -0700 Subject: [PATCH 08/10] chore(datastore): add custom primary key integration tests --- .../cpk_basic_model_operation_test.dart | 253 +++++++++++++++++ ..._has_many_bidirectional_explicit_test.dart | 64 +++++ ..._has_many_bidirectional_implicit_test.dart | 61 +++++ ...y_unidirectional_explicit_parent_test.dart | 65 +++++ ...y_unidirectional_implicit_parent_test.dart | 63 +++++ .../cpk_many_to_many_test.dart | 255 ++++++++++++++++++ ...al_explicit_belongs_to_custom_id_test.dart | 69 +++++ ...idirectional_explicit_belongs_to_test.dart | 65 +++++ ...al_implicit_belongs_to_custom_id_test.dart | 66 +++++ ...idirectional_implicit_belongs_to_test.dart | 62 +++++ ...ne_unidirectional_explicit_child_test.dart | 64 +++++ ...ne_unidirectional_implicit_child_test.dart | 63 +++++ .../cpk_query_relation_test.dart | 61 +++++ .../ModelProvider.dart | 50 ++++ .../ModelProvider.dart | 65 +++++ .../ModelProvider.dart | 60 +++++ .../cpk_many_to_many/ModelProvider.dart | 60 +++++ .../ModelProvider.dart | 60 +++++ .../ModelProvider.dart | 60 +++++ .../ModelProvider.dart | 55 ++++ .../test_cloud_synced_model_operation.dart | 6 +- 21 files changed, 1624 insertions(+), 3 deletions(-) create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_basic_model_operation_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_explicit_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_implicit_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_explicit_parent_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_implicit_parent_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_many_to_many_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_custom_id_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_custom_id_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_explicit_child_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_implicit_child_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_query_relation_test.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/basic_custom_pk_model_operation/ModelProvider.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_bidirectional/ModelProvider.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_unidirectional/ModelProvider.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_many_to_many/ModelProvider.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional/ModelProvider.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional_custom_id/ModelProvider.dart create mode 100644 packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_unidirectional/ModelProvider.dart diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_basic_model_operation_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_basic_model_operation_test.dart new file mode 100644 index 0000000000..9d5c6eae3d --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_basic_model_operation_test.dart @@ -0,0 +1,253 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:amplify_flutter/amplify_flutter.dart'; +import 'package:tuple/tuple.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/basic_custom_pk_model_operation/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + final enableCloudSync = shouldEnableCloudSync(); + const delayDuration = Duration(seconds: 1); + group( + 'Basic model (with Custom PK) operation${enableCloudSync ? ' with API sync 🌩 enabled' : ''} -', + () { + // schema + // type CpkInventory @model { + // productId: ID! @primaryKey(sortKeyFields: ["productName", "warehouseId"]) + // productName: String! + // warehouseId: String! + // description: String + // } + + final testModel = CpkInventory( + productId: UUID.getUUID(), + productName: 'test product', + warehouseId: UUID.getUUID(), + ); + + setUpAll(() async { + await configureDataStore( + enableCloudSync: enableCloudSync, + modelProvider: ModelProvider.instance, + ); + }); + + testWidgets( + 'should save a new model ${enableCloudSync ? 'and sync to cloud' : ''}', + (WidgetTester tester) async { + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [testModel], + expectedRootModelVersion: 1, + rootModelOperator: Amplify.DataStore.save, + rootModelEventsAssertor: (events) { + events.forEach((event) { + expect(event.element.deleted, isFalse); + }); + }, + ); + } else { + await Amplify.DataStore.save(testModel); + } + + var queriedBlogs = await Amplify.DataStore.query(CpkInventory.classType); + expect(queriedBlogs, contains(testModel)); + }); + + testWidgets('query by eq(modelIdentifier) should return a single model', + (WidgetTester tester) async { + final eqResult = await Amplify.DataStore.query( + CpkInventory.classType, + where: CpkInventory.MODEL_IDENTIFIER.eq(testModel.modelIdentifier), + ); + + expect(eqResult.length, 1); + expect(eqResult.first, testModel); + }); + + testWidgets('query by ne(modelIdentifier) should return empty list', + (WidgetTester tester) async { + final eqResult = await Amplify.DataStore.query( + CpkInventory.classType, + where: CpkInventory.MODEL_IDENTIFIER.ne(testModel.modelIdentifier), + ); + + expect(eqResult, isEmpty); + }); + + // TODO: enable after amplify-ios fix the not operator + // testWidgets('query by not(eq(modelIdentifier)) should return empty list', + // (WidgetTester tester) async { + // final eqResult = await Amplify.DataStore.query( + // CpkInventory.classType, + // where: not(CpkInventory.MODEL_IDENTIFIER.eq(testModel.modelIdentifier)), + // ); + + // expect(eqResult, isEmpty); + // }); + + // testWidgets( + // 'query by not(ne(modelIdentifier)) should return a single model', + // (WidgetTester tester) async { + // final eqResult = await Amplify.DataStore.query( + // CpkInventory.classType, + // where: not(CpkInventory.MODEL_IDENTIFIER.ne(testModel.modelIdentifier)), + // ); + + // expect(eqResult.length, 1); + // expect(eqResult.first, testModel); + // }); + + testWidgets( + 'should update existing model ${enableCloudSync ? 'and sync to cloud' : ''}', + (WidgetTester tester) async { + var updatedTestModel = + testModel.copyWith(description: "Newly added description"); + + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [updatedTestModel], + expectedRootModelVersion: 2, + rootModelOperator: Amplify.DataStore.save, + rootModelEventsAssertor: (events) { + events.forEach((event) { + expect(event.element.deleted, isFalse); + }); + }, + ); + } else { + await Amplify.DataStore.save(updatedTestModel); + } + + var queriedBlogs = await Amplify.DataStore.query( + CpkInventory.classType, + where: CpkInventory.MODEL_IDENTIFIER.eq( + updatedTestModel.modelIdentifier, + ), + ); + + expect(queriedBlogs.length, 1); + expect(queriedBlogs.first, updatedTestModel); + }, + ); + + testWidgets( + 'should delete existing model ${enableCloudSync ? 'and sync to cloud' : ''}', + (WidgetTester tester) async { + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [testModel], + expectedRootModelVersion: 3, + rootModelOperator: Amplify.DataStore.delete, + rootModelEventsAssertor: (events) { + events.forEach((event) { + expect(event.element.deleted, isTrue); + }); + }, + ); + } else { + await Amplify.DataStore.delete(testModel); + } + + var queriedBlogs = + await Amplify.DataStore.query(CpkInventory.classType); + + // verify blog was deleted + expect(queriedBlogs, isNot(contains(testModel))); + }, + ); + + testWidgets('observe by model identifier should work', + (WidgetTester tester) async { + final updatedTestModel = + testModel.copyWith(description: "updated description"); + final modelWithDifferentIdentifier = CpkInventory( + productId: UUID.getUUID(), + productName: 'product with different model identifier', + warehouseId: UUID.getUUID(), + ); + + final observeStream = Amplify.DataStore.observe( + CpkInventory.classType, + where: CpkInventory.MODEL_IDENTIFIER.eq(testModel.modelIdentifier), + ).map((event) => Tuple2(event.eventType, event.item)); + + expectLater( + observeStream, + emitsInOrder([ + Tuple2(EventType.create, testModel), + Tuple2(EventType.update, updatedTestModel), + Tuple2(EventType.delete, updatedTestModel), + ]), + ); + + await Future.delayed(delayDuration); + await Amplify.DataStore.save(testModel); + await Amplify.DataStore.save(modelWithDifferentIdentifier); + await Future.delayed(delayDuration); + await Amplify.DataStore.save(updatedTestModel); + await Amplify.DataStore.delete(modelWithDifferentIdentifier); + await Future.delayed(delayDuration); + await Amplify.DataStore.delete(updatedTestModel); + }); + + testWidgets('observeQuery by model identifier should work', + (WidgetTester tester) async { + final updatedTestModel = + testModel.copyWith(description: "updated description"); + final modelWithDifferentIdentifier = CpkInventory( + productId: UUID.getUUID(), + productName: 'product with different model identifier', + warehouseId: UUID.getUUID(), + ); + + final observeStream = Amplify.DataStore.observeQuery( + CpkInventory.classType, + where: CpkInventory.MODEL_IDENTIFIER.eq(testModel.modelIdentifier), + ).map( + (querySnapshot) => Tuple2( + querySnapshot.isSynced, + querySnapshot.items.length > 0 ? querySnapshot.items.first : null, + ), + ); + + expectLater( + observeStream, + emitsInOrder([ + Tuple2(enableCloudSync, null), + Tuple2(enableCloudSync, testModel), + Tuple2(enableCloudSync, updatedTestModel), + Tuple2(enableCloudSync, null), + ]), + ); + + await Future.delayed(delayDuration); + await Amplify.DataStore.save(testModel); + await Amplify.DataStore.save(modelWithDifferentIdentifier); + await Future.delayed(delayDuration); + await Amplify.DataStore.save(updatedTestModel); + await Amplify.DataStore.delete(modelWithDifferentIdentifier); + await Future.delayed(delayDuration); + await Amplify.DataStore.delete(updatedTestModel); + }); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_explicit_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_explicit_test.dart new file mode 100644 index 0000000000..9d872231d9 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_explicit_test.dart @@ -0,0 +1,64 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_has_many_bidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group('HasMany (bi-directional with implicit connection field', () { + // schema + // type HasManyParentBiDirectionalExplicit @model { + // id: ID! + // name: String + // biDirectionalExplicitChildren: [HasManyChildBiDirectionalExplicit] + // @hasMany(indexName: "byHasManyParent", fields: ["id"]) + // } + + // type HasManyChildBiDirectionalExplicit @model { + // id: ID! + // name: String + // hasManyParentId: ID! @index(name: "byHasManyParent", sortKeyFields: ["name"]) + // hasManyParent: HasManyParentBiDirectionalExplicit + // @belongsTo(fields: ["hasManyParentId"]) + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkHasManyParentBidirectionalExplicit(name: 'has many parent (explicit)') + ]; + var associatedModels = List.generate( + 5, + (i) => CpkHasManyChildBidirectionalExplicit( + name: 'has many child $i (explicit)', + hasManyParent: rootModels.first, + ), + ); + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkHasManyParentBidirectionalExplicit.classType, + rootModels: rootModels, + associatedModelType: CpkHasManyChildBidirectionalExplicit.classType, + associatedModels: associatedModels, + supportCascadeDelete: true, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_implicit_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_implicit_test.dart new file mode 100644 index 0000000000..f9227f6dea --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_bidirectional_implicit_test.dart @@ -0,0 +1,61 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_has_many_bidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group('HasMany (bi-directional with implicit connection field', () { + // schema + // type CpkHasManyParentBidirectionalImplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // bidirectionalImplicitChildren: [CpkHasManyChildBidirectionalImplicit] @hasMany + // } + + // type CpkHasManyChildBidirectionalImplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // hasManyParent: CpkHasManyParentBidirectionalImplicit @belongsTo + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkHasManyParentBidirectionalImplicit(name: 'has many parent (explicit)') + ]; + var associatedModels = List.generate( + 5, + (i) => CpkHasManyChildBidirectionalImplicit( + name: 'has many child $i (explicit)', + hasManyParent: rootModels.first, + ), + ); + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkHasManyParentBidirectionalImplicit.classType, + rootModels: rootModels, + associatedModelType: CpkHasManyChildBidirectionalImplicit.classType, + associatedModels: associatedModels, + supportCascadeDelete: true, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_explicit_parent_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_explicit_parent_test.dart new file mode 100644 index 0000000000..ab4fb17632 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_explicit_parent_test.dart @@ -0,0 +1,65 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_has_many_unidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group( + 'HasMany (parent refers to children with explicit connection field and indexName)', + () { + // schema + // type CpkHasManyUnidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // explicitChildren: [CpkHasManyUnidirectionalChildExplicit] + // @hasMany(indexName: "byHasManyParentCpk", fields: ["id", "name"]) + // } + // type CpkHasManyUnidirectionalChildExplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // hasManyParentID: ID! + // @index(name: "byHasManyParentCpk", sortKeyFields: ["hasManyParentName"]) + // hasManyParentName: String! + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkHasManyUnidirectionalParent(name: 'has many parent (explicit)') + ]; + var associatedModels = List.generate( + 5, + (i) => CpkHasManyUnidirectionalChildExplicit( + name: 'has many child $i (explicit)', + hasManyParentID: rootModels.first.id, + hasManyParentName: rootModels.first.name, + ), + ); + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkHasManyUnidirectionalParent.classType, + rootModels: rootModels, + associatedModelType: CpkHasManyUnidirectionalChildExplicit.classType, + associatedModels: associatedModels, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_implicit_parent_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_implicit_parent_test.dart new file mode 100644 index 0000000000..b5f5f03929 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_has_many_unidirectional_implicit_parent_test.dart @@ -0,0 +1,63 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_has_many_unidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group( + 'HasMany (parent refers to children with explicit connection field and indexName)', + () { + // schema + // type CpkHasManyUnidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // implicitChildren: [CpkHasManyUnidirectionalChildImplicit] @hasMany + // } + + // type CpkHasManyUnidirectionalChildImplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkHasManyUnidirectionalParent(name: 'has many parent (implicit)') + ]; + var associatedModels = List.generate( + 5, + (i) => CpkHasManyUnidirectionalChildImplicit( + name: 'has many child $i (implicit)', + cpkHasManyUnidirectionalParentImplicitChildrenId: rootModels.first.id, + cpkHasManyUnidirectionalParentImplicitChildrenName: + rootModels.first.name, + ), + ); + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkHasManyUnidirectionalParent.classType, + rootModels: rootModels, + associatedModelType: CpkHasManyUnidirectionalChildImplicit.classType, + associatedModels: associatedModels, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_many_to_many_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_many_to_many_test.dart new file mode 100644 index 0000000000..29b986f179 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_many_to_many_test.dart @@ -0,0 +1,255 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:amplify_flutter/amplify_flutter.dart'; +import 'package:tuple/tuple.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_many_to_many/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group('Custom Primary Key Many-to-many', () { + // schema + // type CpkManyToManyPost @model { + // id: ID! + // title: String! + // tags: [CpkManyToManyTag] @manyToMany(relationName: "CpkPostTags") + // } + + // type CpkManyToManyTag @model { + // id: ID! @primaryKey(sortKeyFields: ["label"]) + // label: String! + // posts: [CpkManyToManyPost] @manyToMany(relationName: "CpkPostTags") + // } + final enableCloudSync = shouldEnableCloudSync(); + var posts = [ + CpkManyToManyPost(title: 'many to many post 1'), + CpkManyToManyPost(title: 'many to many post 2'), + ]; + var tags = [ + CpkManyToManyTag(label: 'many to many tag 1'), + CpkManyToManyTag(label: 'many to maby tag 2') + ]; + var postTags = [ + CpkPostTags(cpkManyToManyPost: posts[0], cpkManyToManyTag: tags[0]), + CpkPostTags(cpkManyToManyPost: posts[0], cpkManyToManyTag: tags[0]), + CpkPostTags(cpkManyToManyPost: posts[1], cpkManyToManyTag: tags[1]), + CpkPostTags(cpkManyToManyPost: posts[1], cpkManyToManyTag: tags[1]) + ]; + late Future>> + postModelEventsGetter; + late Future>> tagModelEventsGetter; + late Future>> postTagsModelEventsGetter; + + setUpAll(() async { + await configureDataStore( + enableCloudSync: enableCloudSync, + modelProvider: ModelProvider.instance); + + postModelEventsGetter = createObservedEventsGetter( + CpkManyToManyPost.classType, + take: posts.length, + eventType: EventType.create, + ); + tagModelEventsGetter = createObservedEventsGetter( + CpkManyToManyTag.classType, + take: tags.length, + eventType: EventType.create, + ); + postTagsModelEventsGetter = createObservedEventsGetter( + CpkPostTags.classType, + take: postTags.length, + eventType: EventType.create, + ); + }); + + expectModelsNotToBeInLocalStorage([ + Tuple2(CpkManyToManyPost.classType, posts), + Tuple2(CpkManyToManyTag.classType, tags), + Tuple2(CpkPostTags.classType, postTags), + ]); + + testWidgets('save post', (WidgetTester tester) async { + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: posts, + expectedRootModelVersion: 1, + rootModelOperator: Amplify.DataStore.save, + rootModelEventsAssertor: modelIsNotDeletedAssertor, + ); + } else { + for (var post in posts) { + await Amplify.DataStore.save(post); + } + } + + var queriedPosts = + await Amplify.DataStore.query(CpkManyToManyPost.classType); + expect(queriedPosts, containsAll(posts)); + }); + + testWidgets('save tags', (WidgetTester tester) async { + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: tags, + expectedRootModelVersion: 1, + rootModelOperator: Amplify.DataStore.save, + rootModelEventsAssertor: modelIsNotDeletedAssertor, + ); + } else { + for (var tag in tags) { + await Amplify.DataStore.save(tag); + } + } + var queriedTags = + await Amplify.DataStore.query(CpkManyToManyTag.classType); + expect(queriedTags, containsAll(tags)); + }); + + testWidgets('save postTags', (WidgetTester tester) async { + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: postTags, + expectedRootModelVersion: 1, + rootModelOperator: Amplify.DataStore.save, + rootModelEventsAssertor: modelIsNotDeletedAssertor, + ); + } else { + for (var postTag in postTags) { + await Amplify.DataStore.save(postTag); + } + } + + var queriedPostTags = + await Amplify.DataStore.query(CpkPostTags.classType); + expect(queriedPostTags, containsAll(postTags)); + }); + + testWidgets('observe posts', (WidgetTester tester) async { + var events = await postModelEventsGetter; + expectObservedEventsToMatchModels(events: events, referenceModels: posts); + }); + + testWidgets('observe tags', (WidgetTester tester) async { + var events = await tagModelEventsGetter; + expectObservedEventsToMatchModels(events: events, referenceModels: tags); + }); + + testWidgets('observe postTags', (WidgetTester tester) async { + var events = await postTagsModelEventsGetter; + expectObservedEventsToMatchModels( + events: events, referenceModels: postTags); + }); + + testWidgets('delete post (cascade delete associated postTag)', + (WidgetTester tester) async { + var deletedPost = posts[0]; + var deletedPostTags = postTags.getRange(0, 2).toList(); + + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [deletedPost], + expectedRootModelVersion: 2, + rootModelOperator: Amplify.DataStore.delete, + rootModelEventsAssertor: modelIsDeletedAssertor, + associatedModels: deletedPostTags, + expectedAssociatedModelVersion: 2, + associatedModelEventsAssertor: modelIsDeletedAssertor, + ); + } else { + await Amplify.DataStore.delete(deletedPost); + } + + var queriedPosts = + await Amplify.DataStore.query(CpkManyToManyPost.classType); + expect(queriedPosts, isNot(contains(deletedPost))); + + var queriedPostTags = + await Amplify.DataStore.query(CpkPostTags.classType); + expect(queriedPostTags, isNot(containsAll(deletedPostTags))); + }); + + testWidgets('delete tag (cascade delete associated postTag)', + (WidgetTester tester) async { + var deletedTag = tags[1]; + var deletedPostTags = postTags.getRange(2, postTags.length).toList(); + + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [deletedTag], + expectedRootModelVersion: 2, + rootModelOperator: Amplify.DataStore.delete, + rootModelEventsAssertor: modelIsDeletedAssertor, + associatedModels: deletedPostTags, + expectedAssociatedModelVersion: 2, + associatedModelEventsAssertor: modelIsDeletedAssertor, + ); + } else { + await Amplify.DataStore.delete(deletedTag); + } + + var queriedTags = + await Amplify.DataStore.query(CpkManyToManyTag.classType); + expect(queriedTags, isNot(contains(deletedTag))); + + var queriedPostTags = + await Amplify.DataStore.query(CpkPostTags.classType); + expect(queriedPostTags, isNot(containsAll(deletedPostTags))); + }); + + testWidgets('delete remaining post', (WidgetTester tester) async { + var deletedPost = posts[1]; + + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [deletedPost], + expectedRootModelVersion: 2, + rootModelOperator: Amplify.DataStore.delete, + rootModelEventsAssertor: modelIsDeletedAssertor, + ); + } else { + await Amplify.DataStore.delete(deletedPost); + } + + var queriedPosts = + await Amplify.DataStore.query(CpkManyToManyPost.classType); + expect(queriedPosts, isNot(contains(deletedPost))); + }); + + testWidgets('delete remaining tag', (WidgetTester tester) async { + var deletedTag = tags[0]; + + if (enableCloudSync) { + await testCloudSyncedModelOperation( + rootModels: [deletedTag], + expectedRootModelVersion: 2, + rootModelOperator: Amplify.DataStore.delete, + rootModelEventsAssertor: modelIsDeletedAssertor, + ); + } else { + await Amplify.DataStore.delete(deletedTag); + } + + var queriedTags = + await Amplify.DataStore.query(CpkManyToManyTag.classType); + expect(queriedTags, isNot(contains(deletedTag))); + }); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_custom_id_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_custom_id_test.dart new file mode 100644 index 0000000000..7c3f901541 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_custom_id_test.dart @@ -0,0 +1,69 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:amplify_flutter/amplify_flutter.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_one_to_one_bidirectional_custom_id/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group( + 'Bidirectional one-one (child refers parent with explicit fields, parent has custom id)', + () { + // schema + // type CpkOneToOneBidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // explicitChild: CpkOneToOneBidirectionalChildExplicit @hasOne + // } + // + // type CpkOneToOneBidirectionalChildExplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // belongsToParentID: ID + // belongsToParentName: String + // belongsToParent: CpkOneToOneBidirectionalParent + // @belongsTo(fields: ["belongsToParentID", "belongsToParentName"]) + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkOneToOneBidirectionalParentCD( + customId: UUID.getUUID(), + name: "the parent", + ) + ]; + var associatedModels = [ + CpkOneToOneBidirectionalChildExplicitCD( + name: 'belongs to child (explicit)', + belongsToParent: rootModels.first, + ) + ]; + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkOneToOneBidirectionalParentCD.classType, + rootModels: rootModels, + associatedModelType: CpkOneToOneBidirectionalChildExplicitCD.classType, + associatedModels: associatedModels, + supportCascadeDelete: true, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_test.dart new file mode 100644 index 0000000000..7decda2d07 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_explicit_belongs_to_test.dart @@ -0,0 +1,65 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_one_to_one_bidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group('Bidirectional one-one (child refers parent with explicit fields)', () { + // schema + // type CpkOneToOneBidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // explicitChild: CpkOneToOneBidirectionalChildExplicit @hasOne + // } + // + // type CpkOneToOneBidirectionalChildExplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // belongsToParentID: ID + // belongsToParentName: String + // belongsToParent: CpkOneToOneBidirectionalParent + // @belongsTo(fields: ["belongsToParentID", "belongsToParentName"]) + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkOneToOneBidirectionalParentID( + name: "the parent", + ) + ]; + var associatedModels = [ + CpkOneToOneBidirectionalChildExplicitID( + name: 'belongs to child (explicit)', + belongsToParent: rootModels.first, + ) + ]; + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkOneToOneBidirectionalParentID.classType, + rootModels: rootModels, + associatedModelType: CpkOneToOneBidirectionalChildExplicitID.classType, + associatedModels: associatedModels, + supportCascadeDelete: true, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_custom_id_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_custom_id_test.dart new file mode 100644 index 0000000000..de325aec38 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_custom_id_test.dart @@ -0,0 +1,66 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:amplify_flutter/amplify_flutter.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_one_to_one_bidirectional_custom_id/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group( + 'Bidirectional one-one (child refers parent with implicit fields, parent has custom id)', + () { + // schema + // type CpkOneToOneBidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // implicitChild: CpkOneToOneBidirectionalChildImplicit @hasOne + // } + // + // type CpkOneToOneBidirectionalChildImplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // belongsToParent: CpkOneToOneBidirectionalParent @belongsTo + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkOneToOneBidirectionalParentCD( + customId: UUID.getUUID(), + name: "the parent", + ) + ]; + var associatedModels = [ + CpkOneToOneBidirectionalChildImplicitCD( + name: 'belongs to child (explicit)', + belongsToParent: rootModels.first, + ) + ]; + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkOneToOneBidirectionalParentCD.classType, + rootModels: rootModels, + associatedModelType: CpkOneToOneBidirectionalChildImplicitCD.classType, + associatedModels: associatedModels, + supportCascadeDelete: true, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_test.dart new file mode 100644 index 0000000000..368f7b181a --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_bidirectional_implicit_belongs_to_test.dart @@ -0,0 +1,62 @@ +/* + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_one_to_one_bidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group('Bidirectional one-one (child refers parent with implicit fields)', () { + // schema + // type CpkOneToOneBidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // implicitChild: CpkOneToOneBidirectionalChildImplicit @hasOne + // } + // + // type CpkOneToOneBidirectionalChildImplicit @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // belongsToParent: CpkOneToOneBidirectionalParent @belongsTo + // } + final enableCloudSync = shouldEnableCloudSync(); + var rootModels = [ + CpkOneToOneBidirectionalParentID( + name: "the parent", + ) + ]; + var associatedModels = [ + CpkOneToOneBidirectionalChildImplicitID( + name: 'belongs to child (implicit)', + belongsToParent: rootModels.first, + ) + ]; + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkOneToOneBidirectionalParentID.classType, + rootModels: rootModels, + associatedModelType: CpkOneToOneBidirectionalChildImplicitID.classType, + associatedModels: associatedModels, + supportCascadeDelete: true, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_explicit_child_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_explicit_child_test.dart new file mode 100644 index 0000000000..fa68add3f0 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_explicit_child_test.dart @@ -0,0 +1,64 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_one_to_one_unidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group( + 'One-to-one unidirectional (parent refers to child with explicit connection field)', + () { + // type CpkHasOneUnidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // explicitChildID: ID + // explicitChildName: String + // explicitChild: CpkHasOneUnidirectionalChild + // @hasOne(fields: ["explicitChildID", "explicitChildName"]) + // } + // + // type CpkHasOneUnidirectionalChild @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // } + + final enableCloudSync = shouldEnableCloudSync(); + var associatedModels = [CpkHasOneUnidirectionalChild(name: 'child')]; + // Currently with @hasOne, parent -> child relationship is created + // by assign child.id to the connection field of the parent + var rootModels = [ + CpkHasOneUnidirectionalParent( + name: 'HasOne (explicit)', + explicitChildID: associatedModels.first.id, + explicitChildName: associatedModels.first.name, + ), + ]; + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkHasOneUnidirectionalParent.classType, + rootModels: rootModels, + associatedModelType: CpkHasOneUnidirectionalChild.classType, + associatedModels: associatedModels, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_implicit_child_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_implicit_child_test.dart new file mode 100644 index 0000000000..330af8f4ae --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_one_to_one_unidirectional_implicit_child_test.dart @@ -0,0 +1,63 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import '../utils/test_cloud_synced_model_operation.dart'; +import 'models/cpk_one_to_one_unidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + group( + 'One-to-one unidirectional (parent refers to child with explicit connection field)', + () { + // schema + // type CpkHasOneUnidirectionalParent @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // implicitChild: CpkHasOneUnidirectionalChild @hasOne + // } + // + // type CpkHasOneUnidirectionalChild @model { + // id: ID! @primaryKey(sortKeyFields: ["name"]) + // name: String! + // } + + final enableCloudSync = shouldEnableCloudSync(); + var associatedModels = [CpkHasOneUnidirectionalChild(name: 'child')]; + // Currently with @hasOne, parent -> child relationship is created + // by assign child.id to the connection field of the parent + var rootModels = [ + CpkHasOneUnidirectionalParent( + name: 'HasOne (explicit)', + cpkHasOneUnidirectionalParentImplicitChildId: associatedModels.first.id, + cpkHasOneUnidirectionalParentImplicitChildName: + associatedModels.first.name, + ) + ]; + + testRootAndAssociatedModelsRelationship( + modelProvider: ModelProvider.instance, + rootModelType: CpkHasOneUnidirectionalParent.classType, + rootModels: rootModels, + associatedModelType: CpkHasOneUnidirectionalChild.classType, + associatedModels: associatedModels, + enableCloudSync: enableCloudSync, + ); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_query_relation_test.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_query_relation_test.dart new file mode 100644 index 0000000000..afe6e7a54e --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/cpk_query_relation_test.dart @@ -0,0 +1,61 @@ +/* + * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +import 'package:amplify_flutter/amplify_flutter.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../utils/setup_utils.dart'; +import 'models/cpk_has_many_bidirectional/ModelProvider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + var rootModels = [ + CpkHasManyParentBidirectionalExplicit(name: 'has many parent (explicit)') + ]; + var associatedModels = List.generate( + 5, + (i) => CpkHasManyChildBidirectionalExplicit( + name: 'has many child $i (explicit)', + hasManyParent: rootModels.first, + ), + ); + + group('Query child models by the parent model', () { + setUpAll(() async { + await configureDataStore( + enableCloudSync: false, modelProvider: ModelProvider.instance); + + for (var parent in rootModels) await Amplify.DataStore.save(parent); + for (var child in associatedModels) await Amplify.DataStore.save(child); + }); + + test('query child models by parent model identifier', () async { + var queriedModels = await Amplify.DataStore.query( + CpkHasManyChildBidirectionalExplicit.classType, + where: CpkHasManyChildBidirectionalExplicit.HASMANYPARENT.eq( + rootModels.first.modelIdentifier, + ), + ); + + expect(queriedModels, containsAll(associatedModels)); + }); + + tearDownAll(() async { + await clearDataStore(); + }); + }); +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/basic_custom_pk_model_operation/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/basic_custom_pk_model_operation/ModelProvider.dart new file mode 100644 index 0000000000..8dc481320d --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/basic_custom_pk_model_operation/ModelProvider.dart @@ -0,0 +1,50 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkInventory.dart'; + +export '../../../../lib/models/CpkInventory.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "f80fece878bf91a76f44577fe599b120"; + @override + List modelSchemas = [ + CpkInventory.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkInventory": + return CpkInventory.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_bidirectional/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_bidirectional/ModelProvider.dart new file mode 100644 index 0000000000..c72e9674fd --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_bidirectional/ModelProvider.dart @@ -0,0 +1,65 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkHasManyParentBidirectionalExplicit.dart'; +import '../../../../lib/models/CpkHasManyParentBidirectionalImplicit.dart'; +import '../../../../lib/models/CpkHasManyChildBidirectionalExplicit.dart'; +import '../../../../lib/models/CpkHasManyChildBidirectionalImplicit.dart'; + +export '../../../../lib/models/CpkHasManyParentBidirectionalExplicit.dart'; +export '../../../../lib/models/CpkHasManyParentBidirectionalImplicit.dart'; +export '../../../../lib/models/CpkHasManyChildBidirectionalExplicit.dart'; +export '../../../../lib/models/CpkHasManyChildBidirectionalImplicit.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "c4d29b43024b973d2fd3ba65fe7f0a5b"; + @override + List modelSchemas = [ + CpkHasManyParentBidirectionalExplicit.schema, + CpkHasManyParentBidirectionalImplicit.schema, + CpkHasManyChildBidirectionalExplicit.schema, + CpkHasManyChildBidirectionalImplicit.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkHasManyParentBidirectionalExplicit": + return CpkHasManyParentBidirectionalExplicit.classType; + case "CpkHasManyParentBidirectionalImplicit": + return CpkHasManyParentBidirectionalImplicit.classType; + case "CpkHasManyChildBidirectionalExplicit": + return CpkHasManyChildBidirectionalExplicit.classType; + case "CpkHasManyChildBidirectionalImplicit": + return CpkHasManyChildBidirectionalImplicit.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_unidirectional/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_unidirectional/ModelProvider.dart new file mode 100644 index 0000000000..638ea3e409 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_has_many_unidirectional/ModelProvider.dart @@ -0,0 +1,60 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkHasManyUnidirectionalParent.dart'; +import '../../../../lib/models/CpkHasManyUnidirectionalChildImplicit.dart'; +import '../../../../lib/models/CpkHasManyUnidirectionalChildExplicit.dart'; + +export '../../../../lib/models/CpkHasManyUnidirectionalParent.dart'; +export '../../../../lib/models/CpkHasManyUnidirectionalChildImplicit.dart'; +export '../../../../lib/models/CpkHasManyUnidirectionalChildExplicit.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "c4d29b43024b973d2fd3ba65fe7f0a5b"; + @override + List modelSchemas = [ + CpkHasManyUnidirectionalParent.schema, + CpkHasManyUnidirectionalChildImplicit.schema, + CpkHasManyUnidirectionalChildExplicit.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkHasManyUnidirectionalParent": + return CpkHasManyUnidirectionalParent.classType; + case "CpkHasManyUnidirectionalChildImplicit": + return CpkHasManyUnidirectionalChildImplicit.classType; + case "CpkHasManyUnidirectionalChildExplicit": + return CpkHasManyUnidirectionalChildExplicit.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_many_to_many/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_many_to_many/ModelProvider.dart new file mode 100644 index 0000000000..710e87bdae --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_many_to_many/ModelProvider.dart @@ -0,0 +1,60 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkManyToManyPost.dart'; +import '../../../../lib/models/CpkPostTags.dart'; +import '../../../../lib/models/CpkManyToManyTag.dart'; + +export '../../../../lib/models/CpkManyToManyPost.dart'; +export '../../../../lib/models/CpkPostTags.dart'; +export '../../../../lib/models/CpkManyToManyTag.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "c4d29b43024b973d2fd3ba65fe7f0a5b"; + @override + List modelSchemas = [ + CpkManyToManyPost.schema, + CpkPostTags.schema, + CpkManyToManyTag.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkManyToManyPost": + return CpkManyToManyPost.classType; + case "CpkPostTags": + return CpkPostTags.classType; + case "CpkManyToManyTag": + return CpkManyToManyTag.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional/ModelProvider.dart new file mode 100644 index 0000000000..f5ae0c7493 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional/ModelProvider.dart @@ -0,0 +1,60 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkOneToOneBidirectionalParentID.dart'; +import '../../../../lib/models/CpkOneToOneBidirectionalChildExplicitID.dart'; +import '../../../../lib/models/CpkOneToOneBidirectionalChildImplicitID.dart'; + +export '../../../../lib/models/CpkOneToOneBidirectionalParentID.dart'; +export '../../../../lib/models/CpkOneToOneBidirectionalChildExplicitID.dart'; +export '../../../../lib/models/CpkOneToOneBidirectionalChildImplicitID.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "c4d29b43024b973d2fd3ba65fe7f0a5b"; + @override + List modelSchemas = [ + CpkOneToOneBidirectionalParentID.schema, + CpkOneToOneBidirectionalChildExplicitID.schema, + CpkOneToOneBidirectionalChildImplicitID.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkOneToOneBidirectionalParentID": + return CpkOneToOneBidirectionalParentID.classType; + case "CpkOneToOneBidirectionalChildExplicitID": + return CpkOneToOneBidirectionalChildExplicitID.classType; + case "CpkOneToOneBidirectionalChildImplicitID": + return CpkOneToOneBidirectionalChildImplicitID.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional_custom_id/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional_custom_id/ModelProvider.dart new file mode 100644 index 0000000000..607f812bf3 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_bidirectional_custom_id/ModelProvider.dart @@ -0,0 +1,60 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkOneToOneBidirectionalParentCD.dart'; +import '../../../../lib/models/CpkOneToOneBidirectionalChildExplicitCD.dart'; +import '../../../../lib/models/CpkOneToOneBidirectionalChildImplicitCD.dart'; + +export '../../../../lib/models/CpkOneToOneBidirectionalParentCD.dart'; +export '../../../../lib/models/CpkOneToOneBidirectionalChildExplicitCD.dart'; +export '../../../../lib/models/CpkOneToOneBidirectionalChildImplicitCD.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "c4d29b43024b973d2fd3ba65fe7f0a5b"; + @override + List modelSchemas = [ + CpkOneToOneBidirectionalParentCD.schema, + CpkOneToOneBidirectionalChildExplicitCD.schema, + CpkOneToOneBidirectionalChildImplicitCD.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkOneToOneBidirectionalParentCD": + return CpkOneToOneBidirectionalParentCD.classType; + case "CpkOneToOneBidirectionalChildExplicitCD": + return CpkOneToOneBidirectionalChildExplicitCD.classType; + case "CpkOneToOneBidirectionalChildImplicitCD": + return CpkOneToOneBidirectionalChildImplicitCD.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_unidirectional/ModelProvider.dart b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_unidirectional/ModelProvider.dart new file mode 100644 index 0000000000..8e1a292c12 --- /dev/null +++ b/packages/amplify_datastore/example/integration_test/separate_integration_tests/models/cpk_one_to_one_unidirectional/ModelProvider.dart @@ -0,0 +1,55 @@ +/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import '../../../../lib/models/CpkHasOneUnidirectionalParent.dart'; +import '../../../../lib/models/CpkHasOneUnidirectionalChild.dart'; + +export '../../../../lib/models/CpkHasOneUnidirectionalParent.dart'; +export '../../../../lib/models/CpkHasOneUnidirectionalChild.dart'; + +class ModelProvider implements ModelProviderInterface { + @override + String version = "c4d29b43024b973d2fd3ba65fe7f0a5b"; + @override + List modelSchemas = [ + CpkHasOneUnidirectionalParent.schema, + CpkHasOneUnidirectionalChild.schema, + ]; + static final ModelProvider _instance = ModelProvider(); + @override + List customTypeSchemas = []; + + static ModelProvider get instance => _instance; + + ModelType getModelTypeByModelName(String modelName) { + switch (modelName) { + case "CpkHasOneUnidirectionalParent": + return CpkHasOneUnidirectionalParent.classType; + case "CpkHasOneUnidirectionalChild": + return CpkHasOneUnidirectionalChild.classType; + default: + throw Exception( + "Failed to find model in model provider for model name: " + + modelName); + } + } +} diff --git a/packages/amplify_datastore/example/integration_test/utils/test_cloud_synced_model_operation.dart b/packages/amplify_datastore/example/integration_test/utils/test_cloud_synced_model_operation.dart index 1c6f5a7c1c..11d2672be6 100644 --- a/packages/amplify_datastore/example/integration_test/utils/test_cloud_synced_model_operation.dart +++ b/packages/amplify_datastore/example/integration_test/utils/test_cloud_synced_model_operation.dart @@ -65,7 +65,7 @@ Future testCloudSyncedModelOperation({ var model = event.element.model; if (model is R) { - return model.getId() == rootModel.getId() && + return model.modelIdentifier == rootModel.modelIdentifier && event.element.version == expectedRootModelVersion; } @@ -82,7 +82,7 @@ Future testCloudSyncedModelOperation({ var model = event.element.model; if (model is A) { - return model.getId() == associatedModel.getId() && + return model.modelIdentifier == associatedModel.modelIdentifier && event.element.version == expectedRootModelVersion; } @@ -124,7 +124,7 @@ Future>> createObservedEventsGetter( .where((event) => event.eventType == eventType) .distinct((prev, next) => prev.eventType == next.eventType && - prev.item.getId() == next.item.getId()) + prev.item.modelIdentifier == next.item.modelIdentifier) .take(take) .toList(); From 2f3750e408f9fb7c9b3de93d72644bd8f3e5650f Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 18 Jul 2022 12:27:32 -0700 Subject: [PATCH 09/10] chore(datastore): upgrade amplify-android to cpk preview version --- packages/amplify/amplify_flutter_android/android/build.gradle | 4 ++-- packages/amplify_core/android/build.gradle | 2 +- packages/amplify_datastore/android/build.gradle | 4 ++-- .../amplify_analytics_pinpoint_android/android/build.gradle | 4 ++-- packages/api/amplify_api_android/android/build.gradle | 4 ++-- .../auth/amplify_auth_cognito_android/android/build.gradle | 2 +- .../storage/amplify_storage_s3_android/android/build.gradle | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/amplify/amplify_flutter_android/android/build.gradle b/packages/amplify/amplify_flutter_android/android/build.gradle index 9feebc4eb4..38d490f3c0 100644 --- a/packages/amplify/amplify_flutter_android/android/build.gradle +++ b/packages/amplify/amplify_flutter_android/android/build.gradle @@ -72,7 +72,7 @@ android { dependencies { api amplifyCore - implementation 'com.amplifyframework:core:1.36.1' + implementation 'com.amplifyframework:core:v1.37.0-cpkey-preview.2' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' testImplementation 'junit:junit:4.13.2' @@ -81,6 +81,6 @@ dependencies { testImplementation 'androidx.test:core:1.4.0' testImplementation 'org.robolectric:robolectric:4.3.1' testImplementation 'com.google.code.gson:gson:2.8.6' - testImplementation 'com.amplifyframework:aws-auth-cognito:1.36.1' + testImplementation 'com.amplifyframework:aws-auth-cognito:v1.37.0-cpkey-preview.2' testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.9' } diff --git a/packages/amplify_core/android/build.gradle b/packages/amplify_core/android/build.gradle index b5a3924e17..345c07edba 100644 --- a/packages/amplify_core/android/build.gradle +++ b/packages/amplify_core/android/build.gradle @@ -69,7 +69,7 @@ android { } dependencies { - implementation 'com.amplifyframework:core:1.36.1' + implementation 'com.amplifyframework:core:v1.37.0-cpkey-preview.2' implementation 'com.google.code.gson:gson:2.8.6' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' diff --git a/packages/amplify_datastore/android/build.gradle b/packages/amplify_datastore/android/build.gradle index f161953e8c..1f7fa505f2 100644 --- a/packages/amplify_datastore/android/build.gradle +++ b/packages/amplify_datastore/android/build.gradle @@ -69,8 +69,8 @@ android { } dependencies { - implementation "com.amplifyframework:aws-datastore:1.36.1" - implementation "com.amplifyframework:aws-api-appsync:1.36.1" + implementation "com.amplifyframework:aws-datastore:v1.37.0-cpkey-preview.2" + implementation "com.amplifyframework:aws-api-appsync:v1.37.0-cpkey-preview.2" testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:3.10.0' diff --git a/packages/analytics/amplify_analytics_pinpoint_android/android/build.gradle b/packages/analytics/amplify_analytics_pinpoint_android/android/build.gradle index 24ce39aa57..4a84bcc86b 100644 --- a/packages/analytics/amplify_analytics_pinpoint_android/android/build.gradle +++ b/packages/analytics/amplify_analytics_pinpoint_android/android/build.gradle @@ -72,8 +72,8 @@ android { dependencies { api amplifyCore - implementation 'com.amplifyframework:aws-analytics-pinpoint:1.36.1' - implementation 'com.amplifyframework:aws-auth-cognito:1.36.1' + implementation 'com.amplifyframework:aws-analytics-pinpoint:v1.37.0-cpkey-preview.2' + implementation 'com.amplifyframework:aws-auth-cognito:v1.37.0-cpkey-preview.2' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:3.10.0' diff --git a/packages/api/amplify_api_android/android/build.gradle b/packages/api/amplify_api_android/android/build.gradle index 4f114938f6..a206477bee 100644 --- a/packages/api/amplify_api_android/android/build.gradle +++ b/packages/api/amplify_api_android/android/build.gradle @@ -72,8 +72,8 @@ android { dependencies { api amplifyCore - implementation "com.amplifyframework:aws-api:1.36.1" - implementation "com.amplifyframework:aws-api-appsync:1.36.1" + implementation "com.amplifyframework:aws-api:v1.37.0-cpkey-preview.2" + implementation "com.amplifyframework:aws-api-appsync:v1.37.0-cpkey-preview.2" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' testImplementation 'junit:junit:4.13.2' diff --git a/packages/auth/amplify_auth_cognito_android/android/build.gradle b/packages/auth/amplify_auth_cognito_android/android/build.gradle index 17136a0369..943e37ee21 100644 --- a/packages/auth/amplify_auth_cognito_android/android/build.gradle +++ b/packages/auth/amplify_auth_cognito_android/android/build.gradle @@ -74,7 +74,7 @@ android { dependencies { api amplifyCore - implementation 'com.amplifyframework:aws-auth-cognito:1.36.1' + implementation 'com.amplifyframework:aws-auth-cognito:v1.37.0-cpkey-preview.2' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:3.10.0' diff --git a/packages/storage/amplify_storage_s3_android/android/build.gradle b/packages/storage/amplify_storage_s3_android/android/build.gradle index 3659e0d301..e632432d40 100644 --- a/packages/storage/amplify_storage_s3_android/android/build.gradle +++ b/packages/storage/amplify_storage_s3_android/android/build.gradle @@ -62,5 +62,5 @@ android { dependencies { api amplifyCore - implementation 'com.amplifyframework:aws-storage-s3:1.36.1' + implementation 'com.amplifyframework:aws-storage-s3:v1.37.0-cpkey-preview.2' } From 3f81e0bc748633ccf28f48ca494c705b69a2fdbf Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 19 Jul 2022 14:42:40 -0700 Subject: [PATCH 10/10] chore(datastore): upgrade amplify-ios to cpk preview version --- .../amplify_flutter_ios/ios/amplify_flutter_ios.podspec | 6 +++--- packages/amplify_datastore/ios/amplify_datastore.podspec | 4 ++-- .../ios/amplify_analytics_pinpoint_ios.podspec | 4 ++-- packages/api/amplify_api_ios/ios/amplify_api_ios.podspec | 4 ++-- .../ios/amplify_auth_cognito_ios.podspec | 4 ++-- .../ios/amplify_storage_s3_ios.podspec | 4 ++-- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/amplify/amplify_flutter_ios/ios/amplify_flutter_ios.podspec b/packages/amplify/amplify_flutter_ios/ios/amplify_flutter_ios.podspec index 7b39f87014..818fca61ad 100644 --- a/packages/amplify/amplify_flutter_ios/ios/amplify_flutter_ios.podspec +++ b/packages/amplify/amplify_flutter_ios/ios/amplify_flutter_ios.podspec @@ -17,9 +17,9 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/aws-amplify/amplify-flutter.git' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Amplify', '1.25.0' - s.dependency 'AWSPluginsCore', '1.25.0' - s.dependency 'AmplifyPlugins/AWSCognitoAuthPlugin', '1.25.0' + s.dependency 'Amplify', '1.27.1-cpk.1' + s.dependency 'AWSPluginsCore', '1.27.1-cpk.1' + s.dependency 'AmplifyPlugins/AWSCognitoAuthPlugin', '1.27.1-cpk.1' s.dependency 'amplify_core' s.dependency 'SwiftLint' s.dependency 'SwiftFormat/CLI' diff --git a/packages/amplify_datastore/ios/amplify_datastore.podspec b/packages/amplify_datastore/ios/amplify_datastore.podspec index ce3282cd9d..dcfd754310 100644 --- a/packages/amplify_datastore/ios/amplify_datastore.podspec +++ b/packages/amplify_datastore/ios/amplify_datastore.podspec @@ -15,8 +15,8 @@ The DataStore module for Amplify Flutter. s.source = { :git => 'https://github.com/aws-amplify/amplify-flutter.git' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Amplify', '1.25.0' - s.dependency 'AmplifyPlugins/AWSDataStorePlugin', '1.25.0' + s.dependency 'Amplify', '1.27.1-cpk.1' + s.dependency 'AmplifyPlugins/AWSDataStorePlugin', '1.27.1-cpk.1' s.dependency 'amplify_core' s.platform = :ios, '13.0' diff --git a/packages/analytics/amplify_analytics_pinpoint_ios/ios/amplify_analytics_pinpoint_ios.podspec b/packages/analytics/amplify_analytics_pinpoint_ios/ios/amplify_analytics_pinpoint_ios.podspec index cff3413997..710c48c223 100644 --- a/packages/analytics/amplify_analytics_pinpoint_ios/ios/amplify_analytics_pinpoint_ios.podspec +++ b/packages/analytics/amplify_analytics_pinpoint_ios/ios/amplify_analytics_pinpoint_ios.podspec @@ -15,8 +15,8 @@ This code is the iOS part of the Amplify Flutter Pinpoint Analytics Plugin. The s.source = { :git => 'https://github.com/aws-amplify/amplify-flutter.git' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Amplify', '1.25.0' - s.dependency 'AmplifyPlugins/AWSPinpointAnalyticsPlugin', '1.25.0' + s.dependency 'Amplify', '1.27.1-cpk.1' + s.dependency 'AmplifyPlugins/AWSPinpointAnalyticsPlugin', '1.27.1-cpk.1' s.dependency 'amplify_core' s.platform = :ios, '11.0' diff --git a/packages/api/amplify_api_ios/ios/amplify_api_ios.podspec b/packages/api/amplify_api_ios/ios/amplify_api_ios.podspec index 3573bf1965..841b5b52ab 100644 --- a/packages/api/amplify_api_ios/ios/amplify_api_ios.podspec +++ b/packages/api/amplify_api_ios/ios/amplify_api_ios.podspec @@ -15,8 +15,8 @@ The API module for Amplify Flutter. s.source = { :git => 'https://github.com/aws-amplify/amplify-flutter.git' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Amplify', '1.25.0' - s.dependency 'AmplifyPlugins/AWSAPIPlugin', '1.25.0' + s.dependency 'Amplify', '1.27.1-cpk.1' + s.dependency 'AmplifyPlugins/AWSAPIPlugin', '1.27.1-cpk.1' s.dependency 'amplify_core' s.platform = :ios, '11.0' diff --git a/packages/auth/amplify_auth_cognito_ios/ios/amplify_auth_cognito_ios.podspec b/packages/auth/amplify_auth_cognito_ios/ios/amplify_auth_cognito_ios.podspec index 5563d2fb0b..f32a72d60e 100644 --- a/packages/auth/amplify_auth_cognito_ios/ios/amplify_auth_cognito_ios.podspec +++ b/packages/auth/amplify_auth_cognito_ios/ios/amplify_auth_cognito_ios.podspec @@ -15,8 +15,8 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/aws-amplify/amplify-flutter.git' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Amplify', '1.25.0' - s.dependency 'AmplifyPlugins/AWSCognitoAuthPlugin', '1.25.0' + s.dependency 'Amplify', '1.27.1-cpk.1' + s.dependency 'AmplifyPlugins/AWSCognitoAuthPlugin', '1.27.1-cpk.1' s.dependency 'ObjectMapper' s.dependency 'amplify_core' s.platform = :ios, '11.0' diff --git a/packages/storage/amplify_storage_s3_ios/ios/amplify_storage_s3_ios.podspec b/packages/storage/amplify_storage_s3_ios/ios/amplify_storage_s3_ios.podspec index 89a11d0f2f..ec8fd8a5ae 100644 --- a/packages/storage/amplify_storage_s3_ios/ios/amplify_storage_s3_ios.podspec +++ b/packages/storage/amplify_storage_s3_ios/ios/amplify_storage_s3_ios.podspec @@ -15,8 +15,8 @@ Pod::Spec.new do |s| s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Amplify', '1.25.0' - s.dependency 'AmplifyPlugins/AWSS3StoragePlugin', '1.25.0' + s.dependency 'Amplify', '1.27.1-cpk.1' + s.dependency 'AmplifyPlugins/AWSS3StoragePlugin', '1.27.1-cpk.1' s.dependency 'amplify_core' s.platform = :ios, '11.0'